From f61270eb251d71ab2370ef260f3fb06ccc05a09d Mon Sep 17 00:00:00 2001 From: JanardhanBS-SyncByte Date: Wed, 4 Nov 2026 18:19:19 +0530 Subject: [PATCH 1/2] [issue-1633] moved pre-registration-booking-service to pre-registration repo for consolidation Signed-off-by: JanardhanBS-SyncByte --- .github/AGENTS.md | 2 +- .github/workflows/push-trigger.yml | 68 - AGENTS.md | 1 - NOTICE | 3 +- README.md | 83 +- helm/AGENTS.md | 2 +- helm/prereg-booking/README.md | 4 +- kernel/kernel-ref-idobjectvalidator/README.md | 2 +- kernel/kernel-ref-idobjectvalidator/pom.xml | 2 +- licenses/NOTICE | 8 +- pre-registration-booking-service/AGENTS.md | 31 - pre-registration-booking-service/Dockerfile | 49 - pre-registration-booking-service/README.md | 134 -- pre-registration-booking-service/pom.xml | 629 ------ .../run-local.bat | 324 --- pre-registration-booking-service/run-local.sh | 306 --- .../src/main/java/META-INF/MANIFEST.MF | 3 - .../booking/BookingApplication.java | 92 - .../booking/codes/RequestCodes.java | 45 - .../booking/config/BookingConfig.java | 164 -- .../booking/config/OpenApiProperties.java | 68 - .../booking/controller/BookingController.java | 327 --- .../booking/dto/AvailabilityDto.java | 24 - .../booking/dto/AvailabilityReqDto.java | 18 - .../booking/dto/BookingDataByRegIdDto.java | 23 - .../booking/dto/BookingRequestDTO.java | 51 - .../booking/dto/BookingStatus.java | 17 - .../booking/dto/BookingStatusDTO.java | 15 - .../booking/dto/CancelBookingDTO.java | 45 - .../booking/dto/DateTimeDto.java | 27 - .../dto/DemographicBookingRightJoin.java | 43 - .../booking/dto/HolidayDto.java | 38 - .../booking/dto/MultiBookingRequest.java | 20 - .../booking/dto/MultiBookingRequestDTO.java | 57 - .../booking/dto/RegistrationCenterDto.java | 87 - .../dto/RegistrationCenterHolidayDto.java | 22 - .../dto/RegistrationCenterResponseDto.java | 20 - .../preregistration/booking/dto/SlotDto.java | 27 - .../booking/dto/SlotTimeDto.java | 35 - .../booking/entity/AvailabilityPK.java | 48 - .../booking/entity/AvailibityEntity.java | 98 - .../booking/errorcodes/ErrorCodes.java | 75 - .../booking/errorcodes/ErrorMessages.java | 199 -- .../AppointmentAlreadyCanceledException.java | 45 - .../AppointmentBookingFailedException.java | 45 - .../AppointmentCannotBeBookedException.java | 45 - .../AppointmentCannotBeCanceledException.java | 45 - .../AppointmentReBookingFailedException.java | 45 - ...ailabilityTableNotAccessableException.java | 44 - .../AvailabilityUpdationFailedException.java | 45 - .../AvailablityNotFoundException.java | 45 - .../BookingDataNotFoundException.java | 45 - .../BookingDateNotSeletectedException.java | 44 - .../BookingPreIdNotFoundException.java | 45 - ...RegistrationCenterIdNotFoundException.java | 42 - .../BookingTimeSlotAlreadyBooked.java | 45 - ...BookingTimeSlotNotSeletectedException.java | 42 - .../CancelAppointmentFailedException.java | 45 - .../DemographicGetStatusException.java | 43 - .../DemographicStatusUpdationException.java | 44 - .../exception/DocumentNotFoundException.java | 43 - .../InvalidDateTimeFormatException.java | 46 - .../booking/exception/JsonException.java | 45 - .../OperationNotAllowedException.java | 61 - .../exception/RecordNotFoundException.java | 41 - .../booking/exception/TimeSpanException.java | 47 - .../util/BookingExceptionCatcher.java | 184 -- .../util/BookingExceptionHandler.java | 481 ----- .../BookingAvailabilityRepository.java | 153 -- .../repository/DemographicRepository.java | 24 - .../RegistrationBookingRepository.java | 73 - .../booking/repository/impl/BookingDAO.java | 468 ----- .../booking/service/BookingService.java | 1103 ----------- .../booking/service/BookingServiceIntf.java | 173 -- .../booking/service/util/BookingLock.java | 81 - .../service/util/BookingServiceUtil.java | 775 -------- .../src/main/resources/.gitignore | 1 - .../resources/application-local.properties | 168 -- .../src/main/resources/bootstrap.properties | 54 - .../src/main/resources/logback.xml | 11 - .../BookingApplicationComponentScanTest.java | 63 - .../config/BookingConfigOpenApiTest.java | 56 - .../booking/test/BookingApplicationTest.java | 23 - .../booking/test/config/TestConfig.java | 43 - .../test/config/TestSecurityConfig.java | 89 - .../controller/BookingControllerTest.java | 175 -- .../service/BookingServiceCoverageTest.java | 594 ------ .../BookingServiceIdentityMigrationTest.java | 313 --- .../test/service/BookingServiceTest.java | 1763 ----------------- .../service/util/BookingServiceUtilTest.java | 691 ------- .../src/test/resources/application.properties | 176 -- .../src/test/resources/booking.json | 11 - .../src/test/resources/bootstrap.properties | 23 - .../src/test/resources/cancelAppointment.json | 13 - .../src/test/resources/create-schema.sql | 1 - .../src/test/resources/multibooking.json | 16 - 96 files changed, 40 insertions(+), 12132 deletions(-) delete mode 100644 pre-registration-booking-service/AGENTS.md delete mode 100644 pre-registration-booking-service/Dockerfile delete mode 100644 pre-registration-booking-service/README.md delete mode 100644 pre-registration-booking-service/pom.xml delete mode 100644 pre-registration-booking-service/run-local.bat delete mode 100644 pre-registration-booking-service/run-local.sh delete mode 100644 pre-registration-booking-service/src/main/java/META-INF/MANIFEST.MF delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/BookingApplication.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/codes/RequestCodes.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/config/BookingConfig.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/config/OpenApiProperties.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/controller/BookingController.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/AvailabilityDto.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/AvailabilityReqDto.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/BookingDataByRegIdDto.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/BookingRequestDTO.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/BookingStatus.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/BookingStatusDTO.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/CancelBookingDTO.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/DateTimeDto.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/DemographicBookingRightJoin.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/HolidayDto.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/MultiBookingRequest.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/MultiBookingRequestDTO.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/RegistrationCenterDto.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/RegistrationCenterHolidayDto.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/RegistrationCenterResponseDto.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/SlotDto.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/SlotTimeDto.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/entity/AvailabilityPK.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/entity/AvailibityEntity.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/errorcodes/ErrorCodes.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/errorcodes/ErrorMessages.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/AppointmentAlreadyCanceledException.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/AppointmentBookingFailedException.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/AppointmentCannotBeBookedException.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/AppointmentCannotBeCanceledException.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/AppointmentReBookingFailedException.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/AvailabilityTableNotAccessableException.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/AvailabilityUpdationFailedException.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/AvailablityNotFoundException.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/BookingDataNotFoundException.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/BookingDateNotSeletectedException.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/BookingPreIdNotFoundException.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/BookingRegistrationCenterIdNotFoundException.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/BookingTimeSlotAlreadyBooked.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/BookingTimeSlotNotSeletectedException.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/CancelAppointmentFailedException.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/DemographicGetStatusException.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/DemographicStatusUpdationException.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/DocumentNotFoundException.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/InvalidDateTimeFormatException.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/JsonException.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/OperationNotAllowedException.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/RecordNotFoundException.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/TimeSpanException.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/util/BookingExceptionCatcher.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/util/BookingExceptionHandler.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/repository/BookingAvailabilityRepository.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/repository/DemographicRepository.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/repository/RegistrationBookingRepository.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/repository/impl/BookingDAO.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/service/BookingService.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/service/BookingServiceIntf.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/service/util/BookingLock.java delete mode 100644 pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/service/util/BookingServiceUtil.java delete mode 100644 pre-registration-booking-service/src/main/resources/.gitignore delete mode 100644 pre-registration-booking-service/src/main/resources/application-local.properties delete mode 100644 pre-registration-booking-service/src/main/resources/bootstrap.properties delete mode 100644 pre-registration-booking-service/src/main/resources/logback.xml delete mode 100644 pre-registration-booking-service/src/test/java/io/mosip/preregistration/booking/config/BookingApplicationComponentScanTest.java delete mode 100644 pre-registration-booking-service/src/test/java/io/mosip/preregistration/booking/config/BookingConfigOpenApiTest.java delete mode 100644 pre-registration-booking-service/src/test/java/io/mosip/preregistration/booking/test/BookingApplicationTest.java delete mode 100644 pre-registration-booking-service/src/test/java/io/mosip/preregistration/booking/test/config/TestConfig.java delete mode 100644 pre-registration-booking-service/src/test/java/io/mosip/preregistration/booking/test/config/TestSecurityConfig.java delete mode 100644 pre-registration-booking-service/src/test/java/io/mosip/preregistration/booking/test/controller/BookingControllerTest.java delete mode 100644 pre-registration-booking-service/src/test/java/io/mosip/preregistration/booking/test/service/BookingServiceCoverageTest.java delete mode 100644 pre-registration-booking-service/src/test/java/io/mosip/preregistration/booking/test/service/BookingServiceIdentityMigrationTest.java delete mode 100644 pre-registration-booking-service/src/test/java/io/mosip/preregistration/booking/test/service/BookingServiceTest.java delete mode 100644 pre-registration-booking-service/src/test/java/io/mosip/preregistration/booking/test/service/util/BookingServiceUtilTest.java delete mode 100644 pre-registration-booking-service/src/test/resources/application.properties delete mode 100644 pre-registration-booking-service/src/test/resources/booking.json delete mode 100644 pre-registration-booking-service/src/test/resources/bootstrap.properties delete mode 100644 pre-registration-booking-service/src/test/resources/cancelAppointment.json delete mode 100644 pre-registration-booking-service/src/test/resources/create-schema.sql delete mode 100644 pre-registration-booking-service/src/test/resources/multibooking.json diff --git a/.github/AGENTS.md b/.github/AGENTS.md index 5005e6bfe49..1b8a7caa244 100644 --- a/.github/AGENTS.md +++ b/.github/AGENTS.md @@ -12,4 +12,4 @@ Do not glob. Never read `keys/`. └── keys/ # GPG — never read/edit/commit ``` -`push-trigger.yml`: Maven at aggregator (`kernel/`, `registration-processor/`). Docker = child paths. OSSRH skip `master`+PR. Booking Maven `needs` kernel publish; artifact `pre-registration-booking-service` (fat JAR). Regproc Docker artifact `registration-processor`. +`push-trigger.yml`: Maven at aggregator (`kernel/`, `registration-processor/`). Docker = child paths. OSSRH skip `master`+PR. Regproc Docker artifact `registration-processor`. Booking service is not in this repo (mosip/pre-registration). diff --git a/.github/workflows/push-trigger.yml b/.github/workflows/push-trigger.yml index 7902676f266..737177b58a4 100644 --- a/.github/workflows/push-trigger.yml +++ b/.github/workflows/push-trigger.yml @@ -62,74 +62,6 @@ jobs: OSSRH_TOKEN: ${{ secrets.OSSRH_TOKEN }} GPG_SECRET: ${{ secrets.GPG_SECRET }} SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }} - # Booking packages kernel-ref-idobjectvalidator 1.4.1-SNAPSHOT from this repo. - # Wait for kernel publish so Central snapshots has the JAR. On PR/master, publish - # is skipped — still run booking (artifact may already be on snapshots). - build-maven-pre-registration-booking-service: - needs: - - build-maven-kernel - - publish_to_nexus_kernel - if: ${{ always() && needs.build-maven-kernel.result == 'success' && (needs.publish_to_nexus_kernel.result == 'success' || needs.publish_to_nexus_kernel.result == 'skipped') }} - uses: mosip/kattu/.github/workflows/maven-build.yml@master-java21 - with: - SERVICE_LOCATION: pre-registration-booking-service - BUILD_ARTIFACT: pre-registration-booking-service - MAVEN_NON_EXEC_ARTIFACTS: pre-registration-booking-service.jar - secrets: - OSSRH_USER: ${{ secrets.OSSRH_USER }} - OSSRH_SECRET: ${{ secrets.OSSRH_SECRET }} - OSSRH_TOKEN: ${{ secrets.OSSRH_TOKEN }} - GPG_SECRET: ${{ secrets.GPG_SECRET }} - SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }} - build-dockers-pre-registration-booking-service: - needs: build-maven-pre-registration-booking-service - strategy: - matrix: - include: - - SERVICE_LOCATION: 'pre-registration-booking-service' - SERVICE_NAME: 'pre-registration-booking-service' - BUILD_ARTIFACT: 'pre-registration-booking-service' - fail-fast: false - name: ${{ matrix.SERVICE_NAME }} - uses: mosip/kattu/.github/workflows/docker-build.yml@master-java21 - with: - SERVICE_LOCATION: ${{ matrix.SERVICE_LOCATION }} - SERVICE_NAME: ${{ matrix.SERVICE_NAME }} - BUILD_ARTIFACT: ${{ matrix.BUILD_ARTIFACT }} - secrets: - DEV_NAMESPACE_DOCKER_HUB: ${{ secrets.DEV_NAMESPACE_DOCKER_HUB }} - ACTOR_DOCKER_HUB: ${{ secrets.ACTOR_DOCKER_HUB }} - RELEASE_DOCKER_HUB: ${{ secrets.RELEASE_DOCKER_HUB }} - SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }} - - publish_to_nexus_pre-registration-booking-service: - if: "${{ !contains(github.ref, 'master') && github.event_name != 'pull_request' }}" - needs: build-maven-pre-registration-booking-service - uses: mosip/kattu/.github/workflows/maven-publish-to-nexus.yml@master-java21 - with: - SERVICE_LOCATION: pre-registration-booking-service - secrets: - OSSRH_USER: ${{ secrets.OSSRH_USER }} - OSSRH_SECRET: ${{ secrets.OSSRH_SECRET }} - OSSRH_URL: ${{ secrets.OSSRH_CENTRAL_URL }} - OSSRH_TOKEN: ${{ secrets.OSSRH_TOKEN }} - GPG_SECRET: ${{ secrets.GPG_SECRET }} - SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }} - sonar_analysis: - needs: build-maven-pre-registration-booking-service - if: "${{ github.event_name != 'pull_request' }}" - uses: mosip/kattu/.github/workflows/maven-sonar-analysis.yml@master-java21 - with: - SERVICE_LOCATION: pre-registration-booking-service - PROJECT_KEY: mosip_pre-registration-booking-service - secrets: - SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} - ORG_KEY: ${{ secrets.ORG_KEY }} - OSSRH_USER: ${{ secrets.OSSRH_USER }} - OSSRH_SECRET: ${{ secrets.OSSRH_SECRET }} - OSSRH_TOKEN: ${{ secrets.OSSRH_TOKEN }} - GPG_SECRET: ${{ secrets.GPG_SECRET }} - SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }} # Maven runs at registration-processor/ (registration-processor-ref-parent), same pattern as kernel/. # kattu xmlstarlet checks licenses/gpg/git-commit-id on that pom. Children inherit them. diff --git a/AGENTS.md b/AGENTS.md index 5a6d7369104..52591c170d1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -13,7 +13,6 @@ mosip-ref-impl/ │ ├── kernel-smsserviceprovider-msg91/ SMS SPI → AGENTS.md │ └── kernel-virusscanner-clamav/ VirusScanner → AGENTS.md ├── keycloak/ login FTL → AGENTS.md -├── pre-registration-booking-service/ /appointment/** run-local → AGENTS.md ├── registration-processor/ registration-processor-ref-parent → AGENTS.md │ ├── registration-processor-external-stage/ Vert.x → EIS run-local → AGENTS.md │ └── registration-processor-external-integration-service/ EIS stub REST run-local → AGENTS.md diff --git a/NOTICE b/NOTICE index 1100a24294c..2a0c763d78e 100644 --- a/NOTICE +++ b/NOTICE @@ -69,7 +69,7 @@ Apache-2.0 (licenses/Apache-2.0.txt) - io.jsonwebtoken:jjwt-api / jjwt-impl / jjwt-jackson 0.13.0 - org.apache.commons:commons-collections4 4.6.0 - net.logstash.logback:logstash-logback-encoder 9.0 -- com.jayway.jsonpath:json-path 2.10.0 (kernel) / 3.0.0 (booking) +- com.jayway.jsonpath:json-path 2.10.0 (kernel) - net.minidev:json-smart 2.6.0 - org.javassist:javassist 3.33.0-GA (MPL-1.1 OR LGPL-2.1 OR Apache-2.0; MOSIP elects Apache-2.0 — not LGPL) @@ -94,7 +94,6 @@ Mozilla Public License 2.0 (LICENSE) - This repository (mosip-ref-impl modules) - io.mosip.kernel:kernel-core / kernel-auth-adapter 1.4.1-SNAPSHOT -- io.mosip.preregistration:pre-registration-core 1.4.1-SNAPSHOT - io.mosip.registrationprocessor:* 1.4.1-SNAPSHOT - com.h2database:h2 2.4.240 (EPL-1.0 OR MPL-2.0; MOSIP elects MPL-2.0 — not EPL) diff --git a/README.md b/README.md index 1d79f6166c5..782fb3b06a2 100644 --- a/README.md +++ b/README.md @@ -4,12 +4,13 @@ Country-pluggable **reference implementations** (not MOSIP core). Each Maven module is independent, publishes to OSSRH, and can be swapped by dropping in another JAR that implements the same SPI or REST contract. -There is **no repo-root POM** and **no `kernel-bom`**. Standalone modules parent `spring-boot-starter-parent` **4.1.1**. Kernel children inherit through `kernel-ref-parent`; registration-processor children inherit through `registration-processor-ref-parent`. MOSIP library versions (`kernel-core`, `kernel-auth-adapter`, `pre-registration-core`, registration-processor jars) are pinned in each module `pom.xml`, not here. +There is **no repo-root POM** and **no `kernel-bom`**. Standalone modules parent `spring-boot-starter-parent` **4.1.1**. Kernel children inherit through `kernel-ref-parent`; registration-processor children inherit through `registration-processor-ref-parent`. MOSIP library versions (`kernel-core`, `kernel-auth-adapter`, registration-processor jars) are pinned in each module `pom.xml`, not here. ## Contents - [Overview](#overview) - [Repository layout](#repository-layout) +- [Moved: pre-registration-booking-service](#moved-pre-registration-booking-service) - [Prerequisites](#prerequisites) - [Shared facts](#shared-facts) - [Build](#build) @@ -31,12 +32,11 @@ This repository is the reference for how a country can adapt MOSIP: |---|---| | Packet cache | Hazelcast or Redis `PacketCacheProvider` JAR | | Kernel SPIs | ID-object validator, MSG91 SMS, ClamAV virus scanner (`META-INF/spring.factories`) | -| Pre-registration | Booking REST service (`/appointment/**`) | | Registration processor | External stage (Vert.x) + External Integration Service stub REST | | Identity | Keycloak login theme (FTL) | -| Deploy | Helm chart for booking | +| Deploy | Helm chart for booking (`helm/prereg-booking`; service is not in this repo) | -Angular UIs (`pre-registration-ui`, `admin-ui`) live in their own MOSIP repositories, not this tree. Coverage is produced at build time (`mvn clean verify` → `target/site/jacoco/index.html`); TestNG report archives are not checked in. +Angular UIs (`pre-registration-ui`, `admin-ui`) live in their own MOSIP repositories, not this tree. Booking REST (`pre-registration-booking-service`) also lives elsewhere — see [Moved: pre-registration-booking-service](#moved-pre-registration-booking-service). Coverage is produced at build time (`mvn clean verify` → `target/site/jacoco/index.html`); TestNG report archives are not checked in. - - org.springframework.boot - spring-boot-starter-parent - 4.1.1 - - - - io.mosip.preregistration - pre-registration-booking-service - 1.4.1-SNAPSHOT - pre-registration-booking-service - - MOSIP Pre-registration appointment booking REST service. BookingApplication - allow-lists scanBasePackages (booking, pre-registration-core, auth adapter, - logger config, idobjectvalidator) like kernel-notification-service and serves - BookingController under /appointment/** on context /preregistration/v1: - slot availability, single and multi book, get by pre-registration id, cancel, - batch cancel, delete, and centre/date queries. Roles come from the - authorizedRoles bean. Slot contention uses BookingLock (registration centre, - date, timeslot). Spring Boot 4.1.1 parent, Java 21. No kernel-bom. MOSIP pins - (pre-registration-core, kernel-core, kernel-auth-adapter, - kernel-ref-idobjectvalidator) and third-party pins (springdoc, jjwt, - json-path, json-smart, JAXB 2.3 javax line, javassist, - logstash-logback-encoder) live in this pom — not in README.md or AGENTS.md. - kernel-auth-adapter and kernel-ref-idobjectvalidator are packaged in the - service JAR; do not wget them at container start. Logging is in kernel-core - (commons); do not depend on kernel-logger-logback. scanBasePackages includes - io.mosip.kernel.core.logger.config so SleuthLoggingAutoConfiguration loads; - it autowires io.micrometer.tracing.Tracer; - spring-boot-micrometer-tracing-brave registers that bean (the Brave bridge - is already on kernel-core). Jackson 2 via - spring-boot-jackson2 because Boot 4 defaults to Jackson 3. Spring Cloud - Oakwood is imported for config/bootstrap (pre-registration properties). - git-commit-id writes service-git.properties. JaCoCo LINE covered-ratio gate. - Tests are JUnit 4 + Mockito (junit-vintage-engine); Surefire adds - --enable-preview. JVM flags come from Helm prereg-booking javaOpts as - JDK_JAVA_OPTIONS, not from the Dockerfile. CI waits for kernel publish - before this module. - - https://github.com/mosip/mosip-ref-impl - - - 21 - - false - 2025.1.3 - - 3.1.1 - - 0.13.0 - - 9.0 - - 3.0.0 - 2.6.0 - - 3.33.0-GA - - 2.3.9 - 2.3.1 - 3.16.0 - 3.6.0 - 0.8.15 - 5.8.0.7211 - 3.12.0 - 3.4.0 - 3.2.8 - 4.9.10 - 0.11.0 - **/code/**,**/codes/**,**/config/**,**/dao/**,**/dto/**,**/entity/**,**/errorcodes/**,**/exception/**,**/exception/system/**,**/exception/util/**,**/repository/**,**/*Config.java,**/*Application.java,**/batchjob/**,**/util/**,**/stateUtil/** - **/dto/**,**/entity/**,**/config/** - ${project.build.directory}/site/jacoco/jacoco.xml - 0.90 - - - - - 1.4.0-SNAPSHOT - 1.4.1-SNAPSHOT - 1.4.1-SNAPSHOT - 1.4.1-SNAPSHOT - - - - - - - org.springframework.cloud - spring-cloud-dependencies - ${spring-cloud.version} - pom - import - - - - - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-jackson2 - - - - org.springframework.boot - spring-boot-starter-tomcat - provided - - - - org.springframework.boot - spring-boot-starter-security - - - - org.springframework.boot - spring-boot-starter-test - test - - - - org.springframework.security - spring-security-test - test - - - - org.junit.vintage - junit-vintage-engine - test - - - - org.projectlombok - lombok - provided - - - - org.springframework.cloud - spring-cloud-starter-config - - - - org.springframework.boot - spring-boot-devtools - runtime - - - - io.mosip.preregistration - pre-registration-core - ${pre.registration.core.version} - - - - io.mosip.kernel - kernel-core - ${kernel.core.version} - - - - io.mosip.kernel - kernel-auth-adapter - ${kernel.auth.adapter.version} - - - io.mosip.kernel - kernel-ref-idobjectvalidator - ${kernel.ref.idobjectvalidator.version} - - - - io.jsonwebtoken - jjwt-api - ${jjwt.version} - - - io.jsonwebtoken - jjwt-impl - ${jjwt.version} - runtime - - - io.jsonwebtoken - jjwt-jackson - ${jjwt.version} - runtime - - - - com.h2database - h2 - - - - org.postgresql - postgresql - runtime - - - - net.logstash.logback - logstash-logback-encoder - ${logstash-logback-encoder.version} - - - - com.jayway.jsonpath - json-path - ${json-path.version} - - - - net.minidev - json-smart - ${json-smart.version} - - - - io.micrometer - micrometer-core - - - io.micrometer - micrometer-registry-prometheus - - - - org.springframework.boot - spring-boot-micrometer-tracing-brave - - - - javax.xml.bind - jaxb-api - ${jaxb-api-version} - - - - org.glassfish.jaxb - jaxb-runtime - ${jaxb.runtime.version} - - - - org.javassist - javassist - ${javassist.version} - - - - org.springdoc - springdoc-openapi-starter-webmvc-ui - ${springdoc.version} - - - - org.hibernate.validator - hibernate-validator - - - - org.mockito - mockito-core - test - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven.compiler.plugin.version} - - ${java.version} - true - - - org.projectlombok - lombok - ${lombok.version} - - - - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven.surefire.plugin.version} - - ${skipTests} - @{argLine} --add-opens java.xml/jdk.xml.internal=ALL-UNNAMED --add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/java.util=ALL-UNNAMED --enable-preview - - - - org.jacoco - jacoco-maven-plugin - ${maven.jacoco.version} - - - **/code/** - **/codes/** - **/config/** - **/dao/** - **/dto/** - **/entity/** - **/errorcodes/** - **/exception/** - **/repository/** - **/*Config.class - **/*Application.class - **/batchjob/** - **/util/** - **/stateUtil/** - - - - - - prepare-agent - - - - report - prepare-package - - report - - - - jacoco-check - - check - - - - - BUNDLE - - - LINE - COVEREDRATIO - ${jacoco.minimum.coverage} - - - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - true - - - - - build-info - repackage - - - - - - org.apache.maven.plugins - maven-source-plugin - ${maven.source.plugin.version} - - - attach-sources - - jar-no-fork - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - ${maven.javadoc.version} - - - attach-javadocs - - jar - - - - - none - false - - - - org.apache.maven.plugins - maven-gpg-plugin - ${maven.gpg.plugin.version} - - - sign-artifacts - verify - - sign - - - - --pinentry-mode - loopback - - - - - - - pl.project13.maven - git-commit-id-plugin - ${git.commit.id.plugin.version} - - - get-the-git-infos - - revision - - validate - - - - - true - ${project.build.outputDirectory}/service-git.properties - - ^git.build.(time|version)$ - ^git.commit.id.(abbrev|full)$ - - full - ${project.basedir}/.git - - - - org.sonatype.central - central-publishing-maven-plugin - ${central.publishing.maven.plugin.version} - true - - ossrh - false - - - - - - - - sonar - - . - src/main/java/**,src/main/resources/** - ${sonar.coverage.exclusions} - https://sonarcloud.io - - - false - - - - - org.sonarsource.scanner.maven - sonar-maven-plugin - ${maven.sonar.plugin.version} - - - verify - - sonar - - - - - - - - - openapi-doc-generate-profile - - - - io.mosip.kernel - kernel-auth-adapter - ${kernel.auth.adapter.version} - - - - - - - - ossrh - Central Snapshots - https://central.sonatype.com/repository/maven-snapshots/ - - false - - - true - - - - - - scm:git:git://github.com/mosip/mosip-ref-impl.git - scm:git:ssh://github.com:mosip/mosip-ref-impl.git - https://github.com/mosip/mosip-ref-impl - HEAD - - - - MPL 2.0 - https://www.mozilla.org/en-US/MPL/2.0/ - - - - - MOSIP - mosip.emailnotifier@gmail.com - io.mosip - https://github.com/mosip/mosip-ref-impl - - - - - ossrh - https://central.sonatype.com/repository/maven-snapshots/ - - - ossrh - https://central.sonatype.com/api/v1/publisher - - - diff --git a/pre-registration-booking-service/run-local.bat b/pre-registration-booking-service/run-local.bat deleted file mode 100644 index f832594abc0..00000000000 --- a/pre-registration-booking-service/run-local.bat +++ /dev/null @@ -1,324 +0,0 @@ -@echo off -setlocal EnableExtensions EnableDelayedExpansion -REM Standalone Windows cmd runner for pre-registration-booking-service (no .ps1). -REM Linux / macOS / Git Bash: use run-local.sh -REM -REM run-local.bat init | start | smoke | stop | test | all - -set "MODULE_DIR=%~dp0" -if "%MODULE_DIR:~-1%"=="\" set "MODULE_DIR=%MODULE_DIR:~0,-1%" - -set "LOCAL_DIR=%MODULE_DIR%\.local" -set "LOG_DIR=%LOCAL_DIR%\logs" -set "PID_DIR=%LOCAL_DIR%\pids" -set "PID_FILE=%PID_DIR%\booking.pid" -set "LOG_FILE=%LOG_DIR%\booking.log" -set "ERR_FILE=%LOG_DIR%\booking.err.log" -set "MODULE=pre-registration-booking-service" -set "CONTEXT=/preregistration/v1" -set "STARTED=Started BookingApplication" -set "SWAGGER=%CONTEXT%/appointment/booking-service/swagger-ui.html" -set "OPENAPI=%CONTEXT%/appointment/booking-service/v3/api-docs" - -if not defined BOOKING_PORT set "BOOKING_PORT=9095" - -set "CMD=%~1" -if "%CMD%"=="" goto :usage -if /I "%CMD%"=="-h" goto :usage -if /I "%CMD%"=="--help" goto :usage -if /I "%CMD%"=="help" goto :usage -if /I "%CMD%"=="init" goto :init -if /I "%CMD%"=="test" goto :test -if /I "%CMD%"=="start" goto :start -if /I "%CMD%"=="stop" goto :stop -if /I "%CMD%"=="smoke" goto :smoke -if /I "%CMD%"=="all" goto :all - -echo error: unknown command '%CMD%' -goto :usage - -:usage -echo Local pre-registration-booking-service ^(local profile, :9095 /preregistration/v1^) -echo. -echo run-local.bat init package this module -echo run-local.bat start run and wait until Spring Boot is ready -echo run-local.bat smoke GET health + OpenAPI -echo run-local.bat stop -echo run-local.bat test Maven tests -echo run-local.bat all init + test + start + smoke -echo. -echo Port: %BOOKING_PORT% ^(override with set BOOKING_PORT=...^) -echo Config: src\main\resources\application-local.properties -echo Cluster: Dockerfile still uses config-server; it does not activate profile local -exit /b 1 - -:port_in_use -netstat -ano | findstr /R /C:":%BOOKING_PORT% .*LISTENING" >nul 2>&1 -exit /b %ERRORLEVEL% - -:pid_on_port -set "PORT_PID=" -for /f "tokens=5" %%P in ('netstat -ano ^| findstr /R /C:":%BOOKING_PORT% .*LISTENING"') do set "PORT_PID=%%P" -exit /b 0 - -:ensure_dirs -if not exist "%LOG_DIR%" mkdir "%LOG_DIR%" -if not exist "%PID_DIR%" mkdir "%PID_DIR%" -exit /b 0 - -:check_prereqs -where java >nul 2>&1 -if errorlevel 1 ( - echo error: java is required on PATH - exit /b 1 -) -where mvn >nul 2>&1 -if errorlevel 1 ( - echo error: mvn is required on PATH - exit /b 1 -) -exit /b 0 - -:find_jar -set "BOOT_JAR=" -for %%F in ("%MODULE_DIR%\target\%MODULE%-*.jar") do ( - set "CAND=%%~nxF" - echo !CAND! | findstr /I /C:".original" /C:"sources" /C:"javadoc" >nul - if errorlevel 1 ( - set "BOOT_JAR=%%~fF" - goto :find_jar_done - ) -) -:find_jar_done -if not defined BOOT_JAR ( - echo error: no boot jar in target. Run: %~nx0 init - exit /b 1 -) -exit /b 0 - -:is_running -if not exist "%PID_FILE%" exit /b 1 -set /p CHECK_PID=<"%PID_FILE%" -if not defined CHECK_PID exit /b 1 -tasklist /FI "PID eq !CHECK_PID!" 2>nul | findstr /I "!CHECK_PID!" >nul -if errorlevel 1 exit /b 1 -exit /b 0 - -:init -call :check_prereqs -if errorlevel 1 exit /b 1 -call :stop -ping -n 3 127.0.0.1 >nul -echo ==^> packaging %MODULE% ^(skip tests^) -pushd "%MODULE_DIR%" -call mvn clean package -DskipTests "-Dgpg.skip=true" "-Dmaven.javadoc.skip=true" -set "RC=%ERRORLEVEL%" -popd -if not "%RC%"=="0" exit /b %RC% -echo init complete -exit /b 0 - -:test -call :check_prereqs -if errorlevel 1 exit /b 1 -echo ==^> maven tests -pushd "%MODULE_DIR%" -call mvn test "-Dgpg.skip=true" "-Dmaven.javadoc.skip=true" -set "RC=%ERRORLEVEL%" -popd -exit /b %RC% - -:print_urls -echo health http://127.0.0.1:%BOOKING_PORT%%CONTEXT%/actuator/health -echo swagger http://127.0.0.1:%BOOKING_PORT%%SWAGGER% -echo openapi http://127.0.0.1:%BOOKING_PORT%%OPENAPI% -exit /b 0 - -:start -echo. -echo ==^> run-local start -call :ensure_dirs -call :check_prereqs -if errorlevel 1 exit /b 1 -call :is_running -if not errorlevel 1 ( - set /p OLD_PID=<"%PID_FILE%" - echo booking already running ^(pid !OLD_PID!^) on port %BOOKING_PORT% - call :print_urls - exit /b 0 -) -call :port_in_use -if not errorlevel 1 ( - call :pid_on_port - echo booking already listening on port %BOOKING_PORT% ^(pid !PORT_PID!^) - if defined PORT_PID > "%PID_FILE%" echo !PORT_PID! - call :print_urls - exit /b 0 -) -if exist "%PID_FILE%" del /q "%PID_FILE%" >nul 2>&1 -if exist "%LOG_FILE%" del /q "%LOG_FILE%" >nul 2>&1 -if exist "%ERR_FILE%" del /q "%ERR_FILE%" >nul 2>&1 - -call :find_jar -if errorlevel 1 exit /b 1 - -echo ==^> starting booking from %BOOT_JAR% -echo profile=local -echo port=%BOOKING_PORT% -echo context=%CONTEXT% -echo properties=src\main\resources\application-local.properties - -set "LAUNCH_PS1=%LOCAL_DIR%\launch-booking.ps1" -> "%LAUNCH_PS1%" echo $ErrorActionPreference = 'Stop' ->> "%LAUNCH_PS1%" echo $argList = @^('-Dspring.profiles.active=local','-Dserver.port=%BOOKING_PORT%','-Dspring.cloud.config.enabled=false','-jar','%BOOT_JAR%'^) ->> "%LAUNCH_PS1%" echo $p = Start-Process -FilePath 'java' -ArgumentList $argList -WorkingDirectory '%MODULE_DIR%' -RedirectStandardOutput '%LOG_FILE%' -RedirectStandardError '%ERR_FILE%' -WindowStyle Hidden -PassThru ->> "%LAUNCH_PS1%" echo Set-Content -LiteralPath '%PID_FILE%' -Value $p.Id -Encoding ascii -powershell -NoProfile -ExecutionPolicy Bypass -File "%LAUNCH_PS1%" -if errorlevel 1 ( - echo error: failed to start java process - exit /b 1 -) - -echo ==^> waiting for Spring Boot startup on port %BOOKING_PORT% ^(up to 90s^) ... -call :wait_ready 90 -if errorlevel 1 exit /b 1 - -if exist "%PID_FILE%" ( - set /p STARTED_PID=<"%PID_FILE%" - echo pid !STARTED_PID! log %LOG_FILE% -) else ( - call :pid_on_port - if defined PORT_PID ( - > "%PID_FILE%" echo !PORT_PID! - echo pid !PORT_PID! log %LOG_FILE% - ) else ( - echo warn: ready but PID for port %BOOKING_PORT% not resolved - ) -) -echo. -echo booking ready -echo port %BOOKING_PORT% -call :print_urls -exit /b 0 - -:wait_ready -set /a WAIT_MAX=%~1 -if "!WAIT_MAX!"=="" set /a WAIT_MAX=90 -set /a WAIT_ELAPSED=0 -:wait_ready_loop -if !WAIT_ELAPSED! GEQ !WAIT_MAX! goto :wait_ready_fail - -call :port_in_use -if not errorlevel 1 ( - if exist "%LOG_FILE%" ( - findstr /C:"%STARTED%" "%LOG_FILE%" >nul 2>&1 - if not errorlevel 1 exit /b 0 - ) -) - -if exist "%LOG_FILE%" ( - findstr /C:"APPLICATION FAILED TO START" /C:"Port %BOOKING_PORT% was already in use" "%LOG_FILE%" >nul 2>&1 - if not errorlevel 1 ( - echo error: startup failed. See %LOG_FILE% - type "%LOG_FILE%" - exit /b 1 - ) -) - -echo ... still starting ^(!WAIT_ELAPSED!s / !WAIT_MAX!s^) -ping -n 3 127.0.0.1 >nul -set /a WAIT_ELAPSED+=2 -goto :wait_ready_loop - -:wait_ready_fail -echo error: Spring Boot did not become ready within !WAIT_MAX!s on port %BOOKING_PORT% -if exist "%LOG_FILE%" type "%LOG_FILE%" -exit /b 1 - -:stop -call :ensure_dirs -set "STOP_PID=" -if exist "%PID_FILE%" set /p STOP_PID=<"%PID_FILE%" -if not defined STOP_PID ( - call :pid_on_port - set "STOP_PID=!PORT_PID!" -) -if not defined STOP_PID ( - echo booking is not running - exit /b 0 -) -echo ==^> stopping booking ^(%STOP_PID%^) on port %BOOKING_PORT% -taskkill /PID %STOP_PID% /T /F >nul 2>&1 -del /q "%PID_FILE%" >nul 2>&1 -echo stopped. -exit /b 0 - -:http_ok -set "HTTP_CODE=000" -set "HTTP_URL=%~1" -set "HTTP_CODE_FILE=%LOCAL_DIR%\http-code.txt" -curl.exe -sS -o NUL -w "%%{http_code}" --connect-timeout 2 --max-time 3 "%HTTP_URL%" > "%HTTP_CODE_FILE%" 2>nul -if exist "%HTTP_CODE_FILE%" ( - for /f "usebackq delims=" %%C in ("%HTTP_CODE_FILE%") do set "HTTP_CODE=%%C" - del /q "%HTTP_CODE_FILE%" >nul 2>&1 -) -if not defined HTTP_CODE set "HTTP_CODE=000" -if "!HTTP_CODE!"=="" set "HTTP_CODE=000" -exit /b 0 - -:smoke -call :ensure_dirs -echo ==^> waiting for booking ^(up to 60s^) -set /a ELAPSED=0 -:smoke_loop -if %ELAPSED% GEQ 60 goto :smoke_fail -if exist "%PID_FILE%" ( - call :is_running - if errorlevel 1 ( - echo error: process exited. See %LOG_FILE% - if exist "%LOG_FILE%" type "%LOG_FILE%" - if exist "%ERR_FILE%" type "%ERR_FILE%" - exit /b 1 - ) -) -call :http_ok "http://127.0.0.1:%BOOKING_PORT%%CONTEXT%/actuator/health" -if "%HTTP_CODE%"=="200" ( - set "HEALTH_URL=http://127.0.0.1:%BOOKING_PORT%%CONTEXT%/actuator/health" - goto :smoke_ok -) -call :http_ok "http://127.0.0.1:%BOOKING_PORT%/actuator/health" -if "%HTTP_CODE%"=="200" ( - set "HEALTH_URL=http://127.0.0.1:%BOOKING_PORT%/actuator/health" - goto :smoke_ok -) -ping -n 3 127.0.0.1 >nul -set /a ELAPSED+=2 -goto :smoke_loop - -:smoke_ok -echo healthy %HEALTH_URL% -call :http_ok "http://127.0.0.1:%BOOKING_PORT%%OPENAPI%" -echo openapi http://127.0.0.1:%BOOKING_PORT%%OPENAPI% HTTP %HTTP_CODE% -if not "%HTTP_CODE%"=="200" ( - echo error: openapi endpoint not healthy - exit /b 1 -) -echo smoke ok -exit /b 0 - -:smoke_fail -echo error: not healthy. See %LOG_FILE% -if exist "%LOG_FILE%" type "%LOG_FILE%" -if exist "%ERR_FILE%" type "%ERR_FILE%" -exit /b 1 - -:all -echo ==^> all: init + test + start + smoke -call :init -if errorlevel 1 exit /b 1 -call :test -if errorlevel 1 exit /b 1 -call :start -if errorlevel 1 exit /b 1 -call :smoke -exit /b %ERRORLEVEL% diff --git a/pre-registration-booking-service/run-local.sh b/pre-registration-booking-service/run-local.sh deleted file mode 100644 index 50571d69b14..00000000000 --- a/pre-registration-booking-service/run-local.sh +++ /dev/null @@ -1,306 +0,0 @@ -#!/usr/bin/env bash -# pre-registration-booking-service local runner — Linux, macOS, Windows Git Bash/MSYS. -# Windows cmd: use run-local.bat (standalone; no .ps1). -# -# Uses src/main/resources/application-local.properties (profile local). -# No config-server required. Cluster Docker does not activate profile local. -set -euo pipefail - -MODULE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -LOCAL_DIR="${MODULE_DIR}/.local" -LOG_DIR="${LOCAL_DIR}/logs" -PID_DIR="${LOCAL_DIR}/pids" -PORT="${BOOKING_PORT:-9095}" -PID_FILE="${PID_DIR}/booking.pid" -LOG_FILE="${LOG_DIR}/booking.log" -MODULE="pre-registration-booking-service" -UNAME_S="$(uname -s 2>/dev/null || echo unknown)" -CONTEXT="/preregistration/v1" -STARTED="Started BookingApplication" -SWAGGER="${CONTEXT}/appointment/booking-service/swagger-ui.html" -OPENAPI="${CONTEXT}/appointment/booking-service/v3/api-docs" - -MVN_SKIP=( - "-DskipTests" - "-Dgpg.skip=true" - "-Dmaven.javadoc.skip=true" -) - -usage() { - cat <<'EOF' -Local pre-registration-booking-service (local profile, :9095 /preregistration/v1) - - Linux / macOS / Git Bash: - ./run-local.sh init | start | smoke | stop | test | all - - Windows cmd: - run-local.bat init | start | smoke | stop | test | all - -Config: src/main/resources/application-local.properties -Cluster: Dockerfile still uses config-server; it does not activate profile local - - all = init + test + start + smoke -EOF - exit "${1:-0}" -} - -need_cmd() { - command -v "$1" >/dev/null 2>&1 || { - echo "error: '$1' is required on PATH" >&2 - exit 1 - } -} - -ensure_dirs() { - mkdir -p "$LOG_DIR" "$PID_DIR" -} - -check_prereqs() { - need_cmd java - need_cmd mvn - echo "os: ${UNAME_S}" - local ver - ver="$(java -version 2>&1 | head -n 1 || true)" - echo "java: $ver" - if ! echo "$ver" | grep -E '"21[\. "]' >/dev/null 2>&1; then - echo "warn: JDK 21 is required. Continuing anyway." >&2 - fi -} - -find_boot_jar() { - local target="${MODULE_DIR}/target" - local jar - if [[ ! -d "$target" ]]; then - echo "error: not packaged. Run: $0 init" >&2 - exit 1 - fi - for jar in "$target"/${MODULE}-*.jar; do - [[ -f "$jar" ]] || continue - case "$jar" in - *.original|*sources*|*javadoc*) continue ;; - esac - echo "$jar" - return 0 - done - echo "error: no boot jar in ${target}. Run: $0 init" >&2 - exit 1 -} - -is_running() { - [[ -f "$PID_FILE" ]] || return 1 - kill -0 "$(cat "$PID_FILE")" 2>/dev/null -} - -print_urls() { - echo " health http://127.0.0.1:${PORT}${CONTEXT}/actuator/health" - echo " swagger http://127.0.0.1:${PORT}${SWAGGER}" - echo " openapi http://127.0.0.1:${PORT}${OPENAPI}" -} - -cmd_init() { - check_prereqs - cmd_stop - echo "==> packaging ${MODULE} (skip tests)" - (cd "$MODULE_DIR" && mvn clean package "${MVN_SKIP[@]}") - echo "init complete" -} - -cmd_test() { - check_prereqs - echo "==> maven tests" - (cd "$MODULE_DIR" && mvn test "-Dgpg.skip=true" "-Dmaven.javadoc.skip=true") -} - -cmd_start() { - echo - echo "==> run-local start" - ensure_dirs - check_prereqs - if is_running; then - echo "booking already running (pid $(cat "$PID_FILE")) on port ${PORT}" - print_urls - return 0 - fi - rm -f "$LOG_FILE" - local jar - jar="$(find_boot_jar)" - echo "==> starting booking from $(basename "$jar")" - echo " profile=local" - echo " port=${PORT}" - echo " context=${CONTEXT}" - echo " properties=src/main/resources/application-local.properties" - local java_args=( - "-Dspring.profiles.active=local" - "-Dserver.port=${PORT}" - "-Dspring.cloud.config.enabled=false" - ) - java_args+=(-jar "$jar") - nohup java "${java_args[@]}" >"$LOG_FILE" 2>&1 & - echo $! >"$PID_FILE" - echo "pid $(cat "$PID_FILE") log ${LOG_FILE}" - echo "==> waiting for Spring Boot startup on port ${PORT} (up to 90s) ..." - wait_ready 90 - echo - echo "booking ready" - echo " port ${PORT}" - print_urls -} - -wait_ready() { - local timeout="${1:-90}" - local elapsed=0 - local code - while [[ "$elapsed" -lt "$timeout" ]]; do - if ! is_running; then - echo "error: process exited during startup. See ${LOG_FILE}" >&2 - tail -n 80 "$LOG_FILE" >&2 || true - return 1 - fi - if grep -q "${STARTED}" "$LOG_FILE" 2>/dev/null; then - code="$(http_ok "http://127.0.0.1:${PORT}${CONTEXT}/actuator/health")" - if [[ "$code" == "200" ]]; then - return 0 - fi - code="$(http_ok "http://127.0.0.1:${PORT}/actuator/health")" - if [[ "$code" == "200" ]]; then - return 0 - fi - fi - code="$(http_ok "http://127.0.0.1:${PORT}${CONTEXT}/actuator/health")" - if [[ "$code" == "200" ]]; then - return 0 - fi - if grep -q "APPLICATION FAILED TO START\|Port ${PORT} was already in use" "$LOG_FILE" 2>/dev/null; then - echo "error: startup failed. See ${LOG_FILE}" >&2 - tail -n 80 "$LOG_FILE" >&2 || true - return 1 - fi - echo " ... still starting (${elapsed}s / ${timeout}s)" - sleep 2 - elapsed=$((elapsed + 2)) - done - echo "error: Spring Boot did not become ready within ${timeout}s on port ${PORT}" >&2 - tail -n 80 "$LOG_FILE" >&2 || true - return 1 -} - -http_ok() { - local url="$1" - local code - if command -v curl >/dev/null 2>&1; then - code="$(curl -sS -o /dev/null -w "%{http_code}" --connect-timeout 2 --max-time 3 "$url" 2>/dev/null || true)" - [[ -n "$code" ]] || code="000" - printf '%s' "$code" - return 0 - fi - if command -v python3 >/dev/null 2>&1; then - python3 -c 'import sys,urllib.request -try: - urllib.request.urlopen(sys.argv[1], timeout=3) - print("200") -except Exception: - print("000")' "$url" - return 0 - fi - if command -v python >/dev/null 2>&1; then - python -c 'import sys,urllib.request -try: - urllib.request.urlopen(sys.argv[1], timeout=3) - print("200") -except Exception: - print("000")' "$url" - return 0 - fi - echo "error: install curl or python3 for smoke checks" >&2 - printf '%s' "000" -} - -cmd_stop() { - ensure_dirs - if ! is_running; then - rm -f "$PID_FILE" - echo "booking is not running" - return 0 - fi - local pid - pid="$(cat "$PID_FILE")" - echo "==> stopping booking (${pid}) on port ${PORT}" - kill "$pid" 2>/dev/null || true - local i - for i in 1 2 3 4 5 6 7 8 9 10; do - kill -0 "$pid" 2>/dev/null || break - sleep 1 - done - if kill -0 "$pid" 2>/dev/null; then - kill -9 "$pid" 2>/dev/null || true - fi - rm -f "$PID_FILE" - echo "stopped." -} - -cmd_smoke() { - ensure_dirs - local timeout="${1:-60}" - local elapsed=0 - echo "==> waiting for booking (up to ${timeout}s)" - while [[ "$elapsed" -lt "$timeout" ]]; do - if [[ -f "$PID_FILE" ]] && ! is_running; then - echo "error: process exited. See ${LOG_FILE}" >&2 - tail -n 40 "$LOG_FILE" >&2 || true - return 1 - fi - local url code health_url="" - for url in \ - "http://127.0.0.1:${PORT}${CONTEXT}/actuator/health" \ - "http://127.0.0.1:${PORT}/actuator/health" - do - code="$(http_ok "$url")" - if [[ "$code" == "200" ]]; then - health_url="$url" - break - fi - done - if [[ -n "$health_url" ]]; then - echo "healthy ${health_url}" - code="$(http_ok "http://127.0.0.1:${PORT}${OPENAPI}")" - echo "openapi http://127.0.0.1:${PORT}${OPENAPI} HTTP ${code}" - if [[ "$code" != "200" ]]; then - echo "error: openapi endpoint not healthy" >&2 - return 1 - fi - echo "smoke ok" - return 0 - fi - sleep 2 - elapsed=$((elapsed + 2)) - done - echo "error: not healthy. See ${LOG_FILE}" >&2 - tail -n 80 "$LOG_FILE" >&2 || true - return 1 -} - -cmd_all() { - echo "==> all: init + test + start + smoke" - cmd_init - cmd_test - cmd_start - cmd_smoke -} - -main() { - local cmd="${1:-}" - shift || true - case "$cmd" in - -h|--help|help) usage 0 ;; - init) cmd_init ;; - test) cmd_test ;; - start) cmd_start ;; - stop) cmd_stop ;; - smoke) cmd_smoke "${1:-60}" ;; - all) cmd_all ;; - "") usage 1 ;; - *) echo "error: unknown command '$cmd'" >&2; usage 1 ;; - esac -} - -main "$@" diff --git a/pre-registration-booking-service/src/main/java/META-INF/MANIFEST.MF b/pre-registration-booking-service/src/main/java/META-INF/MANIFEST.MF deleted file mode 100644 index 254272e1c07..00000000000 --- a/pre-registration-booking-service/src/main/java/META-INF/MANIFEST.MF +++ /dev/null @@ -1,3 +0,0 @@ -Manifest-Version: 1.0 -Class-Path: - diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/BookingApplication.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/BookingApplication.java deleted file mode 100644 index 3cc6556bcf7..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/BookingApplication.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright - * - */ -package io.mosip.preregistration.booking; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.boot.persistence.autoconfigure.EntityScan; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; - -import io.mosip.kernel.dataaccess.hibernate.repository.impl.HibernateRepositoryImpl; -import io.mosip.preregistration.booking.config.BookingConfig; - -/** - * Starts the Pre-registration booking REST service (Spring Boot 4.1.1). - *

- * Component scan is an allow-list (same pattern as kernel-notification-service - * {@code NotificationBootApplication}): booking, pre-registration-core, auth - * adapter, logger config, and the packaged idobjectvalidator SPI. Do not scan - * {@code io.mosip.*} — kernel-core {@code DataMapperImpl} is a {@code @Component} - * whose {@code Class} constructor Boot 4 cannot autowire. Kernel-core sidecar - * auto-configs are excluded by name; DataSource/JPA stay enabled. Swagger UI - * Authorize is wired in {@link BookingConfig}. - * {@code scanBasePackages} does not register Spring Data repositories or JPA - * entities outside this application's package. BookingServiceUtil autowires - * core {@code UserDetailsService}, which needs {@code UserDetailsRepository} - * from pre-registration-core; {@link EnableJpaRepositories} and - * {@link EntityScan} cover booking plus {@code io.mosip.preregistration.core.common}. - * Kernel {@code BaseRepository.update} is implemented by - * {@link HibernateRepositoryImpl}; Boot's default factory cannot parse that method. - *

- * - * @author Kishan Rathore - * @author Jagadishwari - * @author Ravi C. Balaji - * @since 1.0.0 - * - */ -@SpringBootApplication(scanBasePackages = { - "io.mosip.preregistration.booking.*", - "io.mosip.preregistration.core.*", - "${mosip.auth.adapter.impl.basepackage}", - "io.mosip.kernel.core.logger.config", - "io.mosip.kernel.idobjectvalidator.*" -}) -@EnableJpaRepositories(basePackages = { - "io.mosip.preregistration.booking.repository", - "io.mosip.preregistration.core.common.repository" -}, repositoryBaseClass = HibernateRepositoryImpl.class) -@EntityScan(basePackages = { - "io.mosip.preregistration.booking.entity", - "io.mosip.preregistration.core.common.entity" -}) -@EnableAutoConfiguration(excludeName = { - "io.mosip.kernel.idgenerator.vid.impl.VidGeneratorImpl", - "io.mosip.kernel.idgenerator.vid.util.VidFilterUtils", - "io.mosip.kernel.idgenerator.tokenid.impl.TokenIdGeneratorImpl", - "io.mosip.kernel.idgenerator.machineid.impl.MachineIdGeneratorImpl", - "io.mosip.kernel.idgenerator.regcenterid.impl.RegistrationCenterIdGeneratorImpl", - "io.mosip.kernel.idgenerator.mispid.impl.MispIdGeneratorImpl", - "io.mosip.kernel.licensekeygenerator.misp.impl.MISPLicenseKeyGeneratorImpl", - "io.mosip.kernel.licensekeygenerator.misp.util.MISPLicenseKeyGeneratorUtil", - "io.mosip.kernel.idgenerator.rid.impl.RidGeneratorImpl", - "io.mosip.kernel.idvalidator.prid.impl.PridValidatorImpl", - "io.mosip.kernel.idvalidator.rid.impl.RidValidatorImpl", - "io.mosip.kernel.idvalidator.uin.impl.UinValidatorImpl", - "io.mosip.kernel.idvalidator.vid.impl.VidValidatorImpl", - "io.mosip.kernel.idvalidator.mispid.impl.MispIdValidatorImpl", - "io.mosip.kernel.pdfgenerator.impl.PDFGeneratorImpl", - "io.mosip.kernel.qrcode.generator.zxing.QrcodeGeneratorImpl", - "io.mosip.kernel.transliteration.icu4j.impl.TransliterationImpl", - "io.mosip.kernel.applicanttype.api.impl.ApplicantTypeImpl", - "io.mosip.kernel.idobjectvalidator.config.IdObjectValidatorConfig", - "io.mosip.kernel.websub.api.config.IntentVerificationConfig", - "io.mosip.kernel.websub.api.config.WebSubClientConfig", - "io.mosip.kernel.websub.api.config.publisher.WebSubPublisherClientConfig", - "io.mosip.kernel.websub.api.config.publisher.RestTemplateHelper" -}) -@EnableConfigurationProperties(BookingConfig.class) -public class BookingApplication { - /** - * Method to start the Booking API service. - * - * @param args Spring Boot arguments - */ - public static void main(String[] args) { - SpringApplication.run(BookingApplication.class, args); - } -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/codes/RequestCodes.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/codes/RequestCodes.java deleted file mode 100644 index c78f5a1a616..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/codes/RequestCodes.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.mosip.preregistration.booking.codes; - -/** - * JSON / persistence field names used when reading MOSIP booking requests. - */ -public enum RequestCodes { - - /** Envelope id. */ - id("id"), - - /** Envelope version. */ - version("version"), - - /** Envelope request timestamp. */ - requesttime("requesttime"), - - /** Envelope request object. */ - request("request"), - - /** Pre-registration identifier. */ - PRE_REGISTRAION_ID("preRegistrationId"), - - /** Appointment date column / JSON key. */ - REG_DATE("appointment_date"), - - /** Slot start time column / JSON key. */ - FROM_SLOT_TIME("time_slot_from"); - - /** - * @param code wire or column name - */ - private RequestCodes(String code) { - this.code = code; - } - - /** Canonical code stored with this enum constant. */ - private final String code; - - /** - * @return the wire or column name - */ - public String getCode() { - return code; - } -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/config/BookingConfig.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/config/BookingConfig.java deleted file mode 100644 index 11d6634ab4a..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/config/BookingConfig.java +++ /dev/null @@ -1,164 +0,0 @@ - -/* - * Copyright - * - */ -package io.mosip.preregistration.booking.config; - -import java.util.Collections; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springdoc.core.models.GroupedOpenApi; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import io.swagger.v3.oas.models.Components; -import io.swagger.v3.oas.models.OpenAPI; -import io.swagger.v3.oas.models.info.Info; -import io.swagger.v3.oas.models.info.License; -import io.swagger.v3.oas.models.security.SecurityRequirement; -import io.swagger.v3.oas.models.security.SecurityScheme; -import io.swagger.v3.oas.models.servers.Server; - - -/** - * This class is used for Swagger / Springdoc configuration, host and port helpers, - * and MOSIP booking id maps. - *

- * {@link #openApi()} registers an Authorize apiKey named - * {@code Authorization} (header), same pattern as commons kernel-auth-service. - *

- * - * @author Kishan Rathore - * @author Jagadishwari - * @author Ravi C. Balaji - * @since 1.0.0 - * - */ -@Configuration -@ConfigurationProperties("mosip.preregistration.booking") -public class BookingConfig { - - /** The id. */ - private Map id; - - /** - * Sets the id. - * - * @param id the id - */ - public void setId(Map id) { - this.id = id; - } - - - /** - * Id. - * - * @return the map - */ - @Bean - public Map ic() { - return Collections.unmodifiableMap(id); - } - - /** - * Reference for ${application.env.local:false} from property file. - */ - @Value("${application.env.local:false}") - private Boolean localEnv; - - /** - * Reference for ${swagger.base-url:#{null}} from property file. - */ - @Value("${swagger.base-url:#{null}}") - private String swaggerBaseUrl; - - /** - * Reference for ${server.port:9095} from property file. - */ - @Value("${server.port:9095}") - private int serverPort; - - /** - * To define Protocol - */ - String proto = "http"; - /** - * To define Host - */ - String host = "localhost"; - /** - * To define port - */ - int port = -1; - String hostWithPort = "localhost:9095"; - - /** - * @return set or protocols - */ - private Set protocols() { - Set protocols = new HashSet<>(); - protocols.add(proto); - return protocols; - } - - private static final Logger logger = LoggerFactory.getLogger(BookingConfig.class); - - /** - * Scheme name shown by Swagger UI as Authorize (IDA-style Authorization apiKey). - */ - public static final String AUTHORIZATION_SCHEME = "Authorization"; - - @Autowired - private OpenApiProperties openApiProperties; - - @Bean - public OpenAPI openApi() { - OpenAPI api = new OpenAPI() - .components(new Components().addSecuritySchemes(AUTHORIZATION_SCHEME, authorizationApiKey())) - .addSecurityItem(new SecurityRequirement().addList(AUTHORIZATION_SCHEME)) - .info(new Info() - .title(openApiProperties.getInfo().getTitle()) - .version(openApiProperties.getInfo().getVersion()) - .description(openApiProperties.getInfo().getDescription()) - .license(new License() - .name(openApiProperties.getInfo().getLicense().getName()) - .url(openApiProperties.getInfo().getLicense().getUrl()))); - - openApiProperties.getService().getServers().forEach(server -> { - api.addServersItem(new Server().description(server.getDescription()).url(server.getUrl())); - }); - logger.info("swagger open api bean is ready"); - return api; - } - - /** - * Header apiKey named {@code Authorization} so Swagger UI shows Authorize - * with Name / In / Value (same as commons kernel-auth-service). - * - * @return the security scheme - */ - private static SecurityScheme authorizationApiKey() { - return new SecurityScheme().type(SecurityScheme.Type.APIKEY).in(SecurityScheme.In.HEADER) - .name(AUTHORIZATION_SCHEME); - } - - @Bean - public GroupedOpenApi groupedOpenApi() { - return GroupedOpenApi.builder().group(openApiProperties.getGroup().getName()) - .pathsToMatch(openApiProperties.getGroup().getPaths().stream().toArray(String[]::new)) - .build(); - } - -} - - - diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/config/OpenApiProperties.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/config/OpenApiProperties.java deleted file mode 100644 index 963ff70ad5f..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/config/OpenApiProperties.java +++ /dev/null @@ -1,68 +0,0 @@ -package io.mosip.preregistration.booking.config; - -import lombok.Data; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Configuration; -import java.util.List; - -/** - * Binds {@code openapi.*} properties used by {@link BookingConfig} for Springdoc. - */ -@Configuration -@ConfigurationProperties(prefix = "openapi") -@Data -public class OpenApiProperties { - /** API title, description, version, and license. */ - private InfoProperty info; - /** Published server URLs for the OpenAPI document. */ - private Service service; - /** Swagger UI group name and path filters. */ - private Group group; -} - -/** OpenAPI info block bound from {@code openapi.info.*}. */ -@Data -class InfoProperty { - /** Display title in Swagger UI. */ - private String title; - /** Longer description of the API. */ - private String description; - /** Document version string. */ - private String version; - /** License name and URL. */ - private LicenseProperty license; -} - -/** License fields bound from {@code openapi.info.license.*}. */ -@Data -class LicenseProperty { - /** License display name (for example Mosip). */ - private String name; - /** License document URL. */ - private String url; -} - -/** Server list bound from {@code openapi.service.*}. */ -@Data -class Service { - /** OpenAPI servers (Try-it-out base URLs). */ - private List servers; -} - -/** A single OpenAPI server URL and description. */ -@Data -class Server { - /** Human-readable server label. */ - private String description; - /** Absolute or relative base URL. */ - private String url; -} - -/** Path group bound from {@code openapi.group.*}. */ -@Data -class Group { - /** Springdoc group name. */ - private String name; - /** Ant-style paths included in this group. */ - private List paths; -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/controller/BookingController.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/controller/BookingController.java deleted file mode 100644 index e3b6b5193db..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/controller/BookingController.java +++ /dev/null @@ -1,327 +0,0 @@ -/* - * Copyright - * - */ -package io.mosip.preregistration.booking.controller; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.format.annotation.DateTimeFormat; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.validation.Errors; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.WebDataBinder; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.InitBinder; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -import io.mosip.kernel.core.exception.ParseException; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.preregistration.booking.dto.AvailabilityDto; -import io.mosip.preregistration.booking.dto.BookingDataByRegIdDto; -import io.mosip.preregistration.booking.dto.BookingRequestDTO; -import io.mosip.preregistration.booking.dto.BookingStatus; -import io.mosip.preregistration.booking.dto.BookingStatusDTO; -import io.mosip.preregistration.booking.dto.MultiBookingRequest; -import io.mosip.preregistration.booking.service.BookingServiceIntf; -import io.mosip.preregistration.core.common.dto.BookingRegistrationDTO; -import io.mosip.preregistration.core.common.dto.CancelBookingResponseDTO; -import io.mosip.preregistration.core.common.dto.DeleteBookingDTO; -import io.mosip.preregistration.core.common.dto.MainRequestDTO; -import io.mosip.preregistration.core.common.dto.MainResponseDTO; -import io.mosip.preregistration.core.common.dto.PreRegIdsByRegCenterIdResponseDTO; -import io.mosip.preregistration.core.config.LoggerConfiguration; -import io.mosip.preregistration.core.util.DataValidationUtil; -import io.mosip.preregistration.core.util.RequestValidator; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.media.Content; -import io.swagger.v3.oas.annotations.media.Schema; -import io.swagger.v3.oas.annotations.responses.ApiResponse; -import io.swagger.v3.oas.annotations.responses.ApiResponses; -import io.swagger.v3.oas.annotations.security.SecurityRequirement; -import io.swagger.v3.oas.annotations.tags.Tag; - -/** - * This class provides different API's to perform operations on Booking - * Application - * - * @author Kishan Rathore - * @author Jagadishwari - * @author Ravi C. Balaji - * @since 1.0.0 - * - */ -@RestController -@RequestMapping("/") -@Tag(name = "booking-controller", description = "Booking Controller") -@SecurityRequirement(name = "Authorization") -public class BookingController { - - /** Autowired reference for {@link #bookingService}. */ - @Autowired - private BookingServiceIntf bookingService; - - /** Validates MOSIP request ids on POST/PUT bodies. */ - @Autowired - private RequestValidator requestValidator; - - /** MOSIP request-id constant for booking APIs. */ - private static final String BOOKING = "book"; - - - /** - * Inits the binder. - * - * @param binder the binder - */ - @InitBinder - public void initBinder(WebDataBinder binder) { - binder.addValidators(requestValidator); - } - - - private Logger log = LoggerConfiguration.logConfig(BookingController.class); - - - /** - * Get API to get availability details. - * - * @param registration_center_id - * @return MainResponseDTO - */ - //@PreAuthorize("hasAnyRole('INDIVIDUAL')") - @PreAuthorize("hasAnyRole(@authorizedRoles.getGetappointmentavailability())") - @GetMapping(path = "/appointment/availability/{registrationCenterId}", produces = MediaType.APPLICATION_JSON_VALUE) - @Operation(summary = "Fetch availability Data", description = "Fetch availability Data", tags = "booking-controller") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Availability details fetched successfully"), - @ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "403", description = "Forbidden", content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true))) }) - public ResponseEntity> getAvailability( - @PathVariable("registrationCenterId") String registrationCenterId) { - log.info("sessionId", "idType", "id", - "In getAvailability method of Booking controller to fetch the availability for regID: " - + registrationCenterId); - return ResponseEntity.status(HttpStatus.OK).body(bookingService.getAvailability(registrationCenterId)); - } - - /** - * Post API to book the appointment. - * - * @param MainListRequestDTO - * @return MainResponseDTO - * @throws ParseException - * @throws java.text.ParseException - */ - //@PreAuthorize("hasAnyRole('INDIVIDUAL')") - @PreAuthorize("hasAnyRole(@authorizedRoles.getPostappointmentpreregistrationid())") - @PostMapping(path = "/appointment/{preRegistrationId}", produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) - @Operation(summary = "Booking Appointment", description = "Booking Appointment", tags = "booking-controller") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Appointment Booked Successfully"), - @ApiResponse(responseCode = "201", description = "Created", content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "403", description = "Forbidden", content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true))) }) - public ResponseEntity> bookAppoinment( - @PathVariable("preRegistrationId") String preRegistrationId, - @Validated @RequestBody(required = true) MainRequestDTO bookingDTO, @Parameter(hidden = true) Errors errors ) { - log.info("sessionId", "idType", "id", - "In bookAppoinment method of Booking controller to book an appointment for object: " + bookingDTO); - requestValidator.validateId(BOOKING, bookingDTO.getId(), errors); - DataValidationUtil.validate(errors,BOOKING); - return ResponseEntity.status(HttpStatus.OK).body(bookingService.bookAppointment(bookingDTO, preRegistrationId)); - } - - /** - * Post API to book the appointment. - * - * @param MainListRequestDTO - * @return MainResponseDTO - * @throws ParseException - * @throws java.text.ParseException - */ - //@PreAuthorize("hasAnyRole('INDIVIDUAL')") - @PreAuthorize("hasAnyRole(@authorizedRoles.getPostappointment())") - @PostMapping(path = "/appointment", produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) - @Operation(summary = "Booking Appointment", description = "Booking Appointment", tags = "booking-controller") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Appointment Booked Successfully"), - @ApiResponse(responseCode = "201", description = "Created", content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "403", description = "Forbidden", content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true))) }) - public ResponseEntity> bookMultiAppoinment( - @Validated @RequestBody(required = true) MainRequestDTO bookingRequest, @Parameter(hidden = true) Errors errors) { - log.info("sessionId", "idType", "id", - "In bookAppoinment method of Booking controller to book an appointment for object: " + bookingRequest); - requestValidator.validateId(BOOKING, bookingRequest.getId(), errors); - DataValidationUtil.validate(errors,BOOKING); - return ResponseEntity.status(HttpStatus.OK).body(bookingService.bookMultiAppointment(bookingRequest)); - } - - /** - * Get API to get the booked appointment details. - * - * @param MainListRequestDTO - * @return MainResponseDTO - * @throws ParseException - * @throws java.text.ParseException - */ - - //@PreAuthorize("hasAnyRole('INDIVIDUAL','REGISTRATION_OFFICER','REGISTRATION_SUPERVISOR','REGISTRATION_ ADMIN','PRE_REGISTRATION_ADMIN')") - @PreAuthorize("hasAnyRole(@authorizedRoles.getGetappointmentpreregistrationid())") - @GetMapping(path = "/appointment/{preRegistrationId}", produces = MediaType.APPLICATION_JSON_VALUE) - @Operation(summary = "Fetch Appointment details", description = "Fetch Appointment details", tags = "booking-controller") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Appointment details fetched Successfully"), - @ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "403", description = "Forbidden", content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true))) }) - public ResponseEntity> getAppointments( - @PathVariable("preRegistrationId") String preRegistrationId) { - log.info("sessionId", "idType", "id", - "In appointmentDetails method of Booking controller to fetch appointment details for preRegID: " - + preRegistrationId); - return ResponseEntity.status(HttpStatus.OK).body(bookingService.getAppointmentDetails(preRegistrationId)); - - } - - /** - * Put API to cancel the appointment. - * - * @param MainListRequestDTO - * @return MainResponseDTO - * @throws ParseException - * @throws java.text.ParseException - */ - //@PreAuthorize("hasAnyRole('INDIVIDUAL')") - @PreAuthorize("hasAnyRole(@authorizedRoles.getPutappointmentpreregistrationid())") - @PutMapping(path = "/appointment/{preRegistrationId}", produces = MediaType.APPLICATION_JSON_VALUE) - @Operation(summary = "Cancel an booked appointment", description = "Cancel an booked appointment", tags = "booking-controller") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Appointment canceled successfully"), - @ApiResponse(responseCode = "201", description = "Created", content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "403", description = "Forbidden", content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true))) }) - public ResponseEntity> cancelBook( - @PathVariable("preRegistrationId") String preRegistrationId) { - log.info("sessionId", "idType", "id", - "In cancelBook method of Booking controller to cancel the appointment for object: " + preRegistrationId); - return ResponseEntity.status(HttpStatus.OK) - .body(bookingService.cancelAppointment(preRegistrationId)); - } - - /** - * Put API to cancel the appointment for Pre-registration batch job. - * - * @param MainListRequestDTO - * @return MainResponseDTO - * @throws ParseException - * @throws java.text.ParseException - */ - //@PreAuthorize("hasAnyRole('PRE_REGISTRATION_ADMIN','REGISTRATION_SUPERVISOR')") - @PreAuthorize("hasAnyRole(@authorizedRoles.getPutbatchappointmentpreregistrationid())") - @PutMapping(path = "/batch/appointment/{preRegistrationId}", produces = MediaType.APPLICATION_JSON_VALUE) - @Operation(summary = "Cancel an booked appointment", description = "Cancel an booked appointment", tags = "booking-controller") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Appointment canceled successfully"), - @ApiResponse(responseCode = "201", description = "Created", content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "403", description = "Forbidden", content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true))) }) - public ResponseEntity> cancelAppointmentBatch( - @PathVariable("preRegistrationId") String preRegistrationId) { - log.info("sessionId", "idType", "id", - "In cancelAppointmentBatch method of Booking controller to cancel the appointment for object: " + preRegistrationId+" triggered by batch job"); - return ResponseEntity.status(HttpStatus.OK) - .body(bookingService.cancelAppointmentBatch(preRegistrationId)); - } - - /** - * Delete API to delete the Individual booking associated with the PreId. - * - * @param preId - * the pre id - * @return the deletion status of booking for a pre-id - */ - //@PreAuthorize("hasAnyRole('INDIVIDUAL')") - @PreAuthorize("hasAnyRole(@authorizedRoles.getDeleteappointment())") - @DeleteMapping(path = "/appointment", produces = MediaType.APPLICATION_JSON_VALUE) - @Operation(summary = "Discard Booking", description = "Discard Booking", tags = "booking-controller") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Deletion of Booking is successfully"), - @ApiResponse(responseCode = "201", description = "Created", content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "204", description = "No Content"), - @ApiResponse(responseCode = "401", description = "Unauthorized" ,content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "403", description = "Forbidden" ,content = @Content(schema = @Schema(hidden = true))), - }) - public ResponseEntity> discardIndividual( - @RequestParam(value = "preRegistrationId") String preId) { - log.info("sessionId", "idType", "id", "In Booking controller for deletion of booking with preId " + preId); - - return ResponseEntity.status(HttpStatus.OK).body(bookingService.deleteBooking(preId)); - } - - /** - * Get API to fetch all the booked pre-ids within from-date and to-date range. - * - * @param fromDate - * the from date - * @param toDate - * the to date - * @return the booked pre-ids for date range - */ - //@PreAuthorize("hasAnyRole('INDIVIDUAL','REGISTRATION_OFFICER','REGISTRATION_SUPERVISOR','REGISTRATION_ ADMIN')") - @PreAuthorize("hasAnyRole(@authorizedRoles.getGetappointmentpreregistrationidregistrationcenterid())") - @GetMapping(path = "/appointment/preRegistrationId/{registrationCenterId}", produces = MediaType.APPLICATION_JSON_VALUE) - @Operation(summary = "Get Pre-Registartion ids By Booked Date Time And Registration center id", - description = "Get Pre-Registartion ids By Booked Date Time And Registration center id", tags = "booking-controller") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Booked data successfully retrieved"), - @ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "403", description = "Forbidden", content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true))) }) - public ResponseEntity> getBookedDataByDate( - @RequestParam(value = "from_date", required = true) @DateTimeFormat(pattern = "yyyy-MM-dd") String fromDate, - @RequestParam(value = "to_date") @DateTimeFormat(pattern = "yyyy-MM-dd") String toDate, - @PathVariable("registrationCenterId") String regCenterId) { - log.info("sessionId", "idType", "id", - "In booking controller for fetching all booked preids " + fromDate + " to " + toDate); - return ResponseEntity.status(HttpStatus.OK) - .body(bookingService.getBookedPreRegistrationByDate(fromDate, toDate, regCenterId)); - } - - - /** - * Get API to fetch all the booked pre-ids within from-date and to-date range. - * - * @param fromDate - * the from date - * @param toDate - * the to date - * @return the booked pre-ids for date range - */ - //@PreAuthorize("hasAnyRole('INDIVIDUAL','REGISTRATION_OFFICER','REGISTRATION_SUPERVISOR','REGISTRATION_ ADMIN')") - @PreAuthorize("hasAnyRole(@authorizedRoles.getGetappointmentregistrationcenterid())") - @GetMapping(path = "/appointment/registrationCenterId/{registrationCenterId}", produces = MediaType.APPLICATION_JSON_VALUE) - @Operation(summary = "Get Pre-Registartion ids By Booked Date Time And Registration center id", - description = "Get Pre-Registartion ids By Booked Date Time And Registration center id", tags = "booking-controller") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Booked data successfully retrieved"), - @ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "403", description = "Forbidden", content = @Content(schema = @Schema(hidden = true))), - @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(schema = @Schema(hidden = true))) }) - public ResponseEntity> getBookedDataByRegId( - @RequestParam(value = "from_date", required = true) @DateTimeFormat(pattern = "yyyy-MM-dd") String fromDate, - @RequestParam(value = "to_date") @DateTimeFormat(pattern = "yyyy-MM-dd") String toDate, - @PathVariable("registrationCenterId") String regCenterId) { - log.info("sessionId", "idType", "id", - "In booking controller for fetching all booked preids " + fromDate + " to " + toDate); - return ResponseEntity.status(HttpStatus.OK) - .body(bookingService.getBookedPreRegistrations(fromDate, toDate, regCenterId)); - } -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/AvailabilityDto.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/AvailabilityDto.java deleted file mode 100644 index d0b91e8f9d9..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/AvailabilityDto.java +++ /dev/null @@ -1,24 +0,0 @@ -package io.mosip.preregistration.booking.dto; - -import java.util.List; - -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; -import lombok.ToString; - -/** - * Availability calendar for one registration centre. - */ -@Getter -@Setter -@NoArgsConstructor -@ToString -public class AvailabilityDto { - - /** Registration centre id. */ - private String regCenterId; - - /** Per-day slots (including holidays). */ - private List centerDetails; -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/AvailabilityReqDto.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/AvailabilityReqDto.java deleted file mode 100644 index 2ef79fefc19..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/AvailabilityReqDto.java +++ /dev/null @@ -1,18 +0,0 @@ -package io.mosip.preregistration.booking.dto; - -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; -import lombok.ToString; - -/** - * Request body used to fetch availability for one centre. - */ -@Getter -@Setter -@NoArgsConstructor -@ToString -public class AvailabilityReqDto { - /** Registration centre whose slots are requested. */ - private String registrationCenterId; -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/BookingDataByRegIdDto.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/BookingDataByRegIdDto.java deleted file mode 100644 index d2f50f803cd..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/BookingDataByRegIdDto.java +++ /dev/null @@ -1,23 +0,0 @@ -package io.mosip.preregistration.booking.dto; - -import java.time.LocalDate; -import java.util.Map; - -import lombok.Data; -import lombok.Getter; -import lombok.Setter; - -/** - * Booked pre-ids grouped by appointment date for one registration centre. - */ -@Data -@Getter -@Setter -public class BookingDataByRegIdDto { - - /** Registration centre id. */ - private String registrationCenterId; - - /** pre-id → (date → slot). */ - private Map> idsWithAppointmentDate; -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/BookingRequestDTO.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/BookingRequestDTO.java deleted file mode 100644 index 5d8c5a76062..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/BookingRequestDTO.java +++ /dev/null @@ -1,51 +0,0 @@ -package io.mosip.preregistration.booking.dto; - -import java.io.Serializable; - -import com.fasterxml.jackson.annotation.JsonProperty; - -import io.swagger.annotations.ApiModelProperty; -import lombok.Getter; -import lombok.Setter; - - -/** - * Appointment request: centre, date, and from/to slot. - * - * @author Kishan Rathore - * @since 1.0.0 - */ -@Getter -@Setter -public class BookingRequestDTO implements Serializable{ - /** - * - */ - /** Serialization version. */ - private static final long serialVersionUID = 3339740008361919496L; - /** - * registration Center Id - */ - @JsonProperty("registration_center_id") - @ApiModelProperty(value = "Registration Center ID", position = 1) - private String registrationCenterId; - /** - * booked Date Time - */ - @JsonProperty("appointment_date") - @ApiModelProperty(value = "Appointment Date", position = 2) - private String regDate; - /** - * booked from Time Slot - */ - @JsonProperty("time_slot_from") - @ApiModelProperty(value = "From Time Slot", position = 3) - private String slotFromTime; - /** - * booked to Time Slot - */ - @JsonProperty("time_slot_to") - @ApiModelProperty(value = "To Time Slot", position = 4) - private String slotToTime; - -} \ No newline at end of file diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/BookingStatus.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/BookingStatus.java deleted file mode 100644 index 97b799ececd..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/BookingStatus.java +++ /dev/null @@ -1,17 +0,0 @@ -package io.mosip.preregistration.booking.dto; - -import java.util.List; - -import lombok.Getter; -import lombok.Setter; - -/** - * Multi-appointment response: one status per requested pre-id. - */ -@Getter -@Setter -public class BookingStatus { - - /** Per-pre-id booking outcomes. */ - List bookingStatusResponse; -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/BookingStatusDTO.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/BookingStatusDTO.java deleted file mode 100644 index be5370dac91..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/BookingStatusDTO.java +++ /dev/null @@ -1,15 +0,0 @@ -package io.mosip.preregistration.booking.dto; - -import lombok.Getter; -import lombok.Setter; - -/** - * Single booking outcome message. - */ -@Getter -@Setter -public class BookingStatusDTO { - - /** Human-readable booking result. */ - private String bookingMessage; -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/CancelBookingDTO.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/CancelBookingDTO.java deleted file mode 100644 index e9068a7133b..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/CancelBookingDTO.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.mosip.preregistration.booking.dto; - - -import java.io.Serializable; -import com.fasterxml.jackson.annotation.JsonProperty; - -import io.swagger.annotations.ApiModelProperty; -import lombok.Getter; -import lombok.Setter; - -@Getter -@Setter -public class CancelBookingDTO implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * registration Center Id - */ - @JsonProperty("registration_center_id") - @ApiModelProperty(value = "Registration Center ID", position = 2) - private String registrationCenterId; - /** - * booked Date Time - */ - @JsonProperty("appointment_date") - @ApiModelProperty(value = "Appointment Date", position = 3) - private String regDate; - /** - * booked Time Slot - */ - @JsonProperty("time_slot_from") - @ApiModelProperty(value = "From Time Slot", position = 4) - private String slotFromTime; - - /** - * booked to Time Slot - */ - @JsonProperty("time_slot_to") - @ApiModelProperty(value = "To Time Slot", position = 5) - private String slotToTime; -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/DateTimeDto.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/DateTimeDto.java deleted file mode 100644 index 8c785767d9b..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/DateTimeDto.java +++ /dev/null @@ -1,27 +0,0 @@ -package io.mosip.preregistration.booking.dto; - -import java.util.List; - -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; -import lombok.ToString; - -/** - * One calendar day of slot availability for a centre. - */ -@Getter -@Setter -@NoArgsConstructor -@ToString -public class DateTimeDto { - - /** Calendar date (ISO local date string). */ - private String date; - - /** {@code true} when the centre is closed for a holiday. */ - private boolean isHoliday; - - /** Bookable slots on {@link #date}. */ - private List timeSlots; -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/DemographicBookingRightJoin.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/DemographicBookingRightJoin.java deleted file mode 100644 index 42b2d6ded5e..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/DemographicBookingRightJoin.java +++ /dev/null @@ -1,43 +0,0 @@ -package io.mosip.preregistration.booking.dto; - -import java.io.Serializable; -import java.time.LocalDate; -import java.time.LocalTime; - -import lombok.AllArgsConstructor; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; - -/** - * Join projection of demographic status and booked slot. - */ -@Getter -@Setter -@NoArgsConstructor -@AllArgsConstructor -public class DemographicBookingRightJoin implements Serializable { - - /** - * - */ - /** Serialization version. */ - private static final long serialVersionUID = -6964396778095509912L; - - /** Status of the preid */ - private String statusCode; - - /** Registration center id. */ - private String registrationCenterId; - - /** Slot from time. */ - private LocalTime slotFromTime; - - /** Slot to time. */ - private LocalTime slotToTime; - - /** Appointment date. */ - private LocalDate regDate; - - -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/HolidayDto.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/HolidayDto.java deleted file mode 100644 index f30fbf37ad5..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/HolidayDto.java +++ /dev/null @@ -1,38 +0,0 @@ -package io.mosip.preregistration.booking.dto; - -import java.util.List; - -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; -import lombok.ToString; - -/** - * Holiday row returned with registration-centre masterdata. - */ -@Getter -@Setter -@NoArgsConstructor -@ToString -public class HolidayDto { - /** Holiday identifier. */ - private String holidayId; - /** Calendar date of the holiday. */ - private String holidayDate; - /** - * Holiday day is day of week as integer value, week start from Monday , Monday is 1 and Sunday is 7 - */ - private String holidayDay; - /** - * Holiday month is month of the year as integer value. - */ - private String holidayMonth; - /** Four-digit year. */ - private String holidayYear; - /** Display name of the holiday. */ - private String holidayName; - /** Language of {@link #holidayName}. */ - private String languageCode; - /** Whether the holiday is currently active. */ - private Boolean isActive; -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/MultiBookingRequest.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/MultiBookingRequest.java deleted file mode 100644 index 5b7e2e2e46f..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/MultiBookingRequest.java +++ /dev/null @@ -1,20 +0,0 @@ -package io.mosip.preregistration.booking.dto; - -import java.util.List; - -import lombok.Getter; -import lombok.Setter; - -/** - * Wrapper for several appointment requests in one API call. - * - * @author Kishan Rathore - * @since 1.0.0 - */ -@Getter -@Setter -public class MultiBookingRequest { - - /** Individual booking rows. */ - List bookingRequest; -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/MultiBookingRequestDTO.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/MultiBookingRequestDTO.java deleted file mode 100644 index 1d5e4534e72..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/MultiBookingRequestDTO.java +++ /dev/null @@ -1,57 +0,0 @@ -package io.mosip.preregistration.booking.dto; - -import java.io.Serializable; - -import com.fasterxml.jackson.annotation.JsonProperty; - -import io.mosip.preregistration.core.common.dto.BookingRegistrationDTO; -import io.swagger.annotations.ApiModelProperty; -import lombok.Getter; -import lombok.Setter; - -/** - * One row of a multi-booking request (pre-id plus slot). - * - * @author Kishan Rathore - * @since 1.0.0 - */ -@Getter -@Setter -public class MultiBookingRequestDTO implements Serializable{ - - /** - * - */ - /** Serialization version. */ - private static final long serialVersionUID = -4081838636811604986L; - /** - * pre-Registration Id - */ - @ApiModelProperty(value = "Pre-Registration ID", position = 1) - private String preRegistrationId; - /** - * registration Center Id - */ - @JsonProperty("registration_center_id") - @ApiModelProperty(value = "Registration Center ID", position = 1) - private String registrationCenterId; - /** - * booked Date Time - */ - @JsonProperty("appointment_date") - @ApiModelProperty(value = "Appointment Date", position = 2) - private String regDate; - /** - * booked from Time Slot - */ - @JsonProperty("time_slot_from") - @ApiModelProperty(value = "From Time Slot", position = 3) - private String slotFromTime; - /** - * booked to Time Slot - */ - @JsonProperty("time_slot_to") - @ApiModelProperty(value = "To Time Slot", position = 4) - private String slotToTime; - -} \ No newline at end of file diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/RegistrationCenterDto.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/RegistrationCenterDto.java deleted file mode 100644 index 012e16d5ebd..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/RegistrationCenterDto.java +++ /dev/null @@ -1,87 +0,0 @@ -package io.mosip.preregistration.booking.dto; - -import java.time.LocalTime; - -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; -import lombok.ToString; - -/** - * Registration-centre masterdata used to generate appointment slots. - */ -@Getter -@Setter -@NoArgsConstructor -@ToString -public class RegistrationCenterDto { - - /** Centre identifier. */ - private String id; - - /** Display name. */ - private String name; - - /** Centre type code from masterdata. */ - private String centerTypeCode; - - /** Address line 1. */ - private String addressLine1; - - /** Address line 2. */ - private String addressLine2; - - /** Address line 3. */ - private String addressLine3; - - /** Latitude. */ - private String latitude; - - /** Longitude. */ - private String longitude; - - /** Location hierarchy code. */ - private String locationCode; - - /** Holiday location code used to load holidays. */ - private String holidayLocationCode; - - /** Contact phone. */ - private String contactPhone; - - /** Number of stations at the centre. */ - private Short numberOfStations; - - /** Working-hours description. */ - private String workingHours; - - /** Language of textual fields. */ - private String langCode; - - /** Number of kiosks. */ - private Short numberOfKiosks; - - /** Processing time per kiosk (slot length). */ - private LocalTime perKioskProcessTime; - - /** Centre opening time. */ - private LocalTime centerStartTime; - - /** Centre closing time. */ - private LocalTime centerEndTime; - - /** IANA or MOSIP time zone id. */ - private String timeZone; - - /** Contact person name. */ - private String contactPerson; - - /** Lunch break start. */ - private LocalTime lunchStartTime; - - /** Lunch break end. */ - private LocalTime lunchEndTime; - - /** Whether the centre is active. */ - private Boolean isActive; -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/RegistrationCenterHolidayDto.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/RegistrationCenterHolidayDto.java deleted file mode 100644 index e7e94762274..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/RegistrationCenterHolidayDto.java +++ /dev/null @@ -1,22 +0,0 @@ -package io.mosip.preregistration.booking.dto; - -import java.util.List; - -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; -import lombok.ToString; - -/** - * Masterdata payload: one centre plus its holidays. - */ -@Getter -@Setter -@NoArgsConstructor -@ToString -public class RegistrationCenterHolidayDto { - /** Centre metadata used to generate slots. */ - private RegistrationCenterDto registrationCenter; - /** Holidays for that centre. */ - private List holidays; -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/RegistrationCenterResponseDto.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/RegistrationCenterResponseDto.java deleted file mode 100644 index 62d57558746..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/RegistrationCenterResponseDto.java +++ /dev/null @@ -1,20 +0,0 @@ -package io.mosip.preregistration.booking.dto; - -import java.util.List; - -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; -import lombok.ToString; - -/** - * Masterdata list wrapper for registration centres. - */ -@Getter -@Setter -@NoArgsConstructor -@ToString -public class RegistrationCenterResponseDto { - /** Centres returned by masterdata. */ - private List registrationCenters; -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/SlotDto.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/SlotDto.java deleted file mode 100644 index 38e7489d53d..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/SlotDto.java +++ /dev/null @@ -1,27 +0,0 @@ -package io.mosip.preregistration.booking.dto; - -import java.time.LocalTime; - -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; -import lombok.ToString; - -/** - * A bookable time window and remaining capacity. - */ -@Getter -@Setter -@NoArgsConstructor -@ToString -public class SlotDto { - - /** Slot start (inclusive). */ - private LocalTime fromTime; - - /** Slot end (exclusive or inclusive per MOSIP config). */ - private LocalTime toTime; - - /** Remaining appointments that can still be booked in this slot. */ - private int availability; -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/SlotTimeDto.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/SlotTimeDto.java deleted file mode 100644 index cab008af172..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/dto/SlotTimeDto.java +++ /dev/null @@ -1,35 +0,0 @@ -package io.mosip.preregistration.booking.dto; - -import java.time.LocalTime; - -import lombok.Data; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; -import lombok.ToString; - -/** - * Slot start/end used in booked-pre-id query responses. - */ -@Data -@Getter -@Setter -@NoArgsConstructor -@ToString -public class SlotTimeDto { - - /** Slot start. */ - private LocalTime fromTime; - - /** Slot end. */ - private LocalTime toTime; - - /** - * @param fromTime slot start - * @param toTime slot end - */ - public SlotTimeDto(LocalTime fromTime, LocalTime toTime) { - this.fromTime = fromTime; - this.toTime = toTime; - } -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/entity/AvailabilityPK.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/entity/AvailabilityPK.java deleted file mode 100644 index 609d103bb30..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/entity/AvailabilityPK.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright - * - */ -package io.mosip.preregistration.booking.entity; - -import java.io.Serializable; -import java.time.LocalDate; -import java.time.LocalTime; - -import jakarta.persistence.Column; -import jakarta.persistence.Embeddable; - -import lombok.Getter; -import lombok.Setter; - -/** - * This entity class defines the database table details for Booking application. - * - * @author Kishan Rathore - * @author Jagadishwari - * @author Ravi C. Balaji - * @since 1.0.0 - * - */ -@Embeddable -@Getter -@Setter -public class AvailabilityPK implements Serializable{ - - /** The Constant serialVersionUID. */ - private static final long serialVersionUID = -4022968783477038513L; - - /** Registration_Center_Id. */ - @Column(name = "regcntr_id") - private String regcntrId; - - /** Availability_Date. */ - @Column(name = "availability_date") - private LocalDate regDate; - - /**Slot_From_Time. */ - @Column(name = "slot_from_time") - private LocalTime fromTime; - - - -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/entity/AvailibityEntity.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/entity/AvailibityEntity.java deleted file mode 100644 index 1b620d6aaff..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/entity/AvailibityEntity.java +++ /dev/null @@ -1,98 +0,0 @@ - -/* - * Copyright - * - */ -package io.mosip.preregistration.booking.entity; - -import java.io.Serializable; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.LocalTime; - -import jakarta.persistence.AttributeOverride; -import jakarta.persistence.AttributeOverrides; -import jakarta.persistence.Column; -import jakarta.persistence.Entity; -import jakarta.persistence.Id; -import jakarta.persistence.IdClass; -import jakarta.persistence.NamedQuery; -import jakarta.persistence.Table; - -import org.springframework.stereotype.Component; - -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; -import lombok.ToString; - -/** - * This entity class defines the database table details for Booking application. - * - * @author Kishan Rathore - * @author Jagadishwari - * @author Ravi C. Balaji - * @since 1.0.0 - * - */ -@Component -@Entity -@Table(name = "reg_available_slot", schema = "prereg") -@Getter -@Setter -@NoArgsConstructor -@ToString -@IdClass(AvailabilityPK.class) -@NamedQuery(name = "AvailibityEntity.findDate", query = "SELECT DISTINCT regDate FROM AvailibityEntity where regcntrId=:regcntrId and regDate>=:fromDate and regDate<=:toDate order by regDate ASC") -public class AvailibityEntity implements Serializable { - - /** The Constant serialVersionUID. */ - private static final long serialVersionUID = 1L; - - /** Registration center Id. */ - @Id - @AttributeOverrides({ @AttributeOverride(name = "regcntrId", column = @Column(name = "regcntr_id")), - @AttributeOverride(name = "regDate", column = @Column(name = "availability_date")), - @AttributeOverride(name = "fromTime", column = @Column(name = "slot_from_time")) }) - - private String regcntrId; - - /** Registration date. */ - private LocalDate regDate; - - /** From date. */ - private LocalTime fromTime; - - /** Slot to time. */ - @Column(name = "slot_to_time") - private LocalTime toTime; - - /** Available Kiosks. */ - @Column(name = "available_kiosks") - private int availableKiosks; - - /** Created by. */ - @Column(name = "cr_by") - private String crBy; - - /** Created date time. */ - @Column(name = "cr_dtimes") - private LocalDateTime crDate; - - /** Updated by. */ - @Column(name = "upd_by") - private String upBy; - - /** Updated date time. */ - @Column(name = "upd_dtimes") - private LocalDateTime updDate; - - /** Is deleted. */ - @Column(name = "is_deleted") - private boolean isDeleted; - - /** Delete date time. */ - @Column(name = "del_dtimes") - private LocalDateTime delTime; - -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/errorcodes/ErrorCodes.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/errorcodes/ErrorCodes.java deleted file mode 100644 index 36347da3796..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/errorcodes/ErrorCodes.java +++ /dev/null @@ -1,75 +0,0 @@ - -/* - * Copyright - * - */ -package io.mosip.preregistration.booking.errorcodes; - -/** - * This Enum provides the constant variables to define Error codes. - * - * @author Kishan Rathore - * @author Jagadishwari - * @author Ravi C. Balaji - * @since 1.0.0 - * - */ -public enum ErrorCodes { - PRG_BOOK_RCI_001("PRG_BOOK_RCI_001"), // Appointment cannot be booked - PRG_BOOK_RCI_002("PRG_BOOK_RCI_002"), // availability not thr for selected time - PRG_BOOK_RCI_003("PRG_BOOK_RCI_003"), // User has not been selected any time slot - PRG_BOOK_RCI_004("PRG_BOOK_RCI_004"), // Appointment time slot is already booked - PRG_BOOK_RCI_005("PRG_BOOK_RCI_005"), // Appointment booking failed - PRG_BOOK_RCI_006("PRG_BOOK_RCI_006"), // Pre id not found - PRG_BOOK_RCI_007("PRG_BOOK_RCI_007"), // reg center id not found - PRG_BOOK_RCI_008("PRG_BOOK_RCI_008"), // date is not selected - PRG_BOOK_RCI_010("PRG_BOOK_RCI_010"), // Booking Table not accessible - PRG_BOOK_RCI_011("PRG_BOOK_RCI_011"), // status code updation failed - PRG_BOOK_RCI_012("PRG_BOOK_RCI_012"), // get status code failed - PRG_BOOK_RCI_014("PRG_BOOK_RCI_014"), // no slots available for that date - PRG_BOOK_RCI_015("PRG_BOOK_RCI_015"), // No time slots are assigned to that registration center - PRG_BOOK_RCI_013("PRG_BOOK_RCI_013"), // Booking data not found - PRG_BOOK_RCI_016("PRG_BOOK_RCI_016"), // availability table is not accessable - PRG_BOOK_RCI_017("PRG_BOOK_RCI_017"), // Appointment time slot is already canceled. - PRG_BOOK_RCI_018("PRG_BOOK_RCI_018"), // Appointment can not be canceled. - PRG_BOOK_RCI_019("PRG_BOOK_RCI_019"), // Cancel Appointmenct failed - PRG_BOOK_RCI_020("PRG_BOOK_RCI_020"), // Master service not available - PRG_BOOK_RCI_021("PRG_BOOK_RCI_021"), // Rebooking failed - PRG_BOOK_RCI_022("PRG_BOOK_RCI_022"), // Invalid request parameter - PRG_BOOK_RCI_023("PRG_BOOK_RCI_023"), // DOCUMENTS_NOT_FOUND_EXCEPTION - PRG_BOOK_RCI_024("PRG_BOOK_RCI_024"), // AVAILABILITY_UPDATE_FAILED - PRG_BOOK_RCI_025("PRG_BOOK_RCI_025"), // HTTP_CLIENT_EXCEPTION - PRG_BOOK_RCI_026("PRG_BOOK_RCI_026"), // Booking status cannot be done altered before. - PRG_BOOK_RCI_027("PRG_BOOK_RCI_027"), // Delete Booking not allowed - PRG_BOOK_RCI_028("PRG_BOOK_RCI_028"), // FAILED_TO_DELETE_THE_PRE_REGISTRATION_RECORD - PRG_BOOK_RCI_029("PRG_BOOK_RCI_029"), // APPONIMENT_CANNOT_BE_CANCELED - PRG_BOOK_RCI_030("PRG_BOOK_RCI_030"), - PRG_BOOK_RCI_031("PRG_BOOK_RCI_031"), // Invalid Booking Date Time - PRG_BOOK_RCI_032("PRG_BOOK_RCI_032"),// BOOKING_NOT_FOUND_FOR_THE_DATE_RANGE - PRG_PAM_APP_005("PRG_PAM_APP_005"), // failed to update in demographic entity - PRG_BOOK_RCI_033("PRG_BOOK_RCI_033"),// notification failed exception - PRG_BOOK_RCI_034("PRG_BOOK_RCI_034"), - PRG_BOOK_RCI_035("PRG_BOOK_RCI_035"),// reg center id not found - PRG_BOOK_RCI_036("PRG_BOOK_RCI_036"); //Appointmnet cannot be booked for incomplete application - - - /** - * @param code - */ - private ErrorCodes(String code) { - this.code = code; - } - - /** - * Code - */ - private final String code; - - /** - * @return the code - */ - public String getCode() { - return code; - } - -} \ No newline at end of file diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/errorcodes/ErrorMessages.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/errorcodes/ErrorMessages.java deleted file mode 100644 index 219e21d5a5c..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/errorcodes/ErrorMessages.java +++ /dev/null @@ -1,199 +0,0 @@ - -/* - * Copyright - * - */ -package io.mosip.preregistration.booking.errorcodes; - -/** - * This Enum provides the constant variables to define Error Messages. - * - * @author Kishan Rathore - * @author Jagadishwari - * @author Ravi C. Balaji - * @since 1.0.0 - * - */ -/** - * @author M1043008 - * - */ -public enum ErrorMessages { - /** - * ErrorMessage for PRG_BOOK_RCI_001 - */ - BOOKING_TABLE_NOT_ACCESSIBLE("Booking table not found"), - /** - * ErrorMessage for PRG_BOOK_RCI_002 - */ - REGISTRATION_TABLE_NOT_ACCESSIBLE("Registration table to accessible"), - /** - * ErrorMessage for PRG_BOOK_RCI_003 - */ - USER_HAS_NOT_SELECTED_TIME_SLOT("User has not selected time slot"), - /** - * ErrorMessage for PRG_BOOK_RCI_004 - */ - APPOINTMENT_TIME_SLOT_IS_ALREADY_BOOKED("Appointment time slot is already booked"), - /** - * ErrorMessage for PRG_TRL_APP_001 - */ - PREREGISTRATION_ID_NOT_ENTERED("Preregistration id not entered"), - /** - * ErrorMessage for PRG_TRL_APP_001 - */ - REGISTRATION_CENTER_ID_NOT_ENTERED("Registration center id not entered"), - /** - * ErrorMessage for PRG_TRL_APP_001 - */ - BOOKING_DATE_TIME_NOT_SELECTED("Booking date time not selected"), - /** - * ErrorMessage for PRG_TRL_APP_001 - */ - INVALID_ID("Invalid id"), - /** - * ErrorMessage for PRG_TRL_APP_001 - */ - INVALID_VERSION("Invalid version"), - /** - * ErrorMessage for PRG_TRL_APP_001 - */ - APPOINTMENT_CANNOT_BE_BOOKED("Appointment cannot be booked"), - /** - * ErrorMessage for PRG_TRL_APP_001 - */ - AVAILABILITY_NOT_FOUND_FOR_THE_SELECTED_TIME( - "Appointment booking/re-booking cannot be done as the requested slot is not available. Please select another slot or try again later"), - /** - * ErrorMessage for PRG_TRL_APP_001 - */ - APPOINTMENT_BOOKING_FAILED("Appointment booking/re-booking cannot be done"), - /** - * ErrorMessage for PRG_TRL_APP_001 - */ - TABLE_NOT_FOUND_EXCEPTION("Table not found exception"), - /** - * ErrorMessage for PRG_TRL_APP_001 - */ - DEMOGRAPHIC_STATUS_UPDATION_FAILED("Demographic status updation failed"), - /** - * ErrorMessage for PRG_TRL_APP_001 - */ - NO_TIME_SLOTS_ASSIGNED_TO_THAT_REG_CENTER("No available slots found for specified registration center"), - /** - * ErrorMessage for PRG_TRL_APP_001 - */ - DEMOGRAPHIC_GET_STATUS_FAILED("Demographic get status failed"), - /** - * ErrorMessage for PRG_TRL_APP_001 - */ - AVAILABILITY_TABLE_NOT_ACCESSABLE("Availablity table not accessible"), - /** - * ErrorMessage for PRG_TRL_APP_001 - */ - BOOKING_DATA_NOT_FOUND("Booking data not found"), - /** - * ErrorMessage for PRG_TRL_APP_001 - */ - APPOINTMENT_CANNOT_BE_CANCELED("Appointment cannot be canceled"), - /** - * ErrorMessage for PRG_TRL_APP_001 - */ - APPOINTMENT_TIME_SLOT_IS_ALREADY_CANCELED("Appointment time slot is already canceled"), - /** - * ErrorMessage for PRG_TRL_APP_001 - */ - APPOINTMENT_CANCEL_FAILED("Appointment cancel failed"), - /** - * ErrorMessage for PRG_TRL_APP_001 - */ - APPOINTMENT_REBOOKING_FAILED("Appointment rebooking failed"), - /** - * ErrorMessage for PRG_TRL_APP_001 - */ - MASTER_DATA_NOT_FOUND("Master data not found"), - /** - * ErrorMessage for PRG_TRL_APP_001 - */ - HOLIDAY_MASTER_DATA_NOT_FOUND("Holiday master data not found"), - /** - * ErrorMessage for PRG_TRL_APP_001 - */ - INVALID_REQUEST_PARAMETER("Invalid request parameter"), - /** - * ErrorMessage for PRG_TRL_APP_001 - */ - DOCUMENTS_NOT_FOUND_EXCEPTION("Documents not found exception"), - /** - * ErrorMessage for PRG_TRL_APP_001 - */ - DEMOGRAPHIC_SERVICE_CALL_FAILED("Demographic service call failed"), - /** - * ErrorMessage for PRG_TRL_APP_001 - */ - AVAILABILITY_UPDATE_FAILED("Availablity update failed"), - /** - * ErrorMessage for PRG_TRL_APP_001 - */ - HTTP_CLIENT_EXCEPTION("Http client exception"), - /** - * ErrorMessage for PRG_TRL_APP_026 - */ - BOOKING_CANNOT_BE_DONE("Appointment re-booking cannot be done within"), - - /** - * ErrorMessage for PRG_TRL_APP_027 - */ - DELETE_BOOKING_NOT_ALLOWED("Delete booking not allowed"), - /** - * ErrorMessage for PRG_TRL_APP_028 - */ - FAILED_TO_DELETE_THE_PRE_REGISTRATION_RECORD("Failed to delete the pre registration record"), - /** - * ErrorMessage for PRG_TRL_APP_029 - */ - APPONIMENT_CANNOT_BE_CANCELED("Appointment cannot be canceled"), - /** - * ErrorMessage for PRG_TRL_APP_030 - */ - CANNOT_GET_DETAILS_FOR("Cannot get details for"), - /** - * ErrorMessage for PRG_BOOK_RCI_032 - */ - RECORD_NOT_FOUND_FOR_DATE_RANGE_AND_REG_CENTER_ID("Record not found for date range and reg center id"), - - /* - * ErrorMessage for PRG_BOOK_RCI_031 - */ - INVALID_BOOKING_DATE_TIME("Invalid Booking Date Time"), - - UNABLE_TO_FETCH_THE_PRE_REGISTRATION("Unable to fetch the pre-registration id"), - - NOTIFICATION_CALL_FAILED("Notification service call failed"), - - JSON_PROCESSING_EXCEPTION("Json processing exception"), - - REG_CENTER_ID_NOT_FOUND("Registration center id not found"), - - APPOINTMENT_CANNOT_BE_BOOKED_FOR_INCOMPLETE_APPLICATION("Appointment cannot be booked for incomplete application"), - - APPOINTMENT_CANNOT_BE_BOOKED_FOR_PREFETCHED_APPLICATION("Appointment cannot be booked for prefetched application"), - - CANCEL_BOOKING_CANNOT_BE_DONE("Appointment cancelling cannot be done within"); - /** - * @param code - */ - private ErrorMessages(String message) { - this.message = message; - } - - private final String message; - - /** - * @return message - */ - public String getMessage() { - return message; - } - -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/AppointmentAlreadyCanceledException.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/AppointmentAlreadyCanceledException.java deleted file mode 100644 index ed03e97a040..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/AppointmentAlreadyCanceledException.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.mosip.preregistration.booking.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.preregistration.core.common.dto.MainResponseDTO; -import lombok.Getter; - -/** - * @author Jagadishwari - * @since 1.0.0 - */ - -@Getter -public class AppointmentAlreadyCanceledException extends BaseUncheckedException { - - /** - * - */ - private static final long serialVersionUID = 5135952690225019228L; - private MainResponseDTO mainResponseDTO; - - public AppointmentAlreadyCanceledException(String msg) { - super("", msg); - } - - public AppointmentAlreadyCanceledException(String msg, Throwable cause) { - super("", msg, cause); - } - - public AppointmentAlreadyCanceledException(String errorCode, String errorMessage) { - super(errorCode, errorMessage, null); - } - - public AppointmentAlreadyCanceledException(String errorCode, String errorMessage,MainResponseDTO response) { - super(errorCode, errorMessage, null); - this.mainResponseDTO=response; - } - - public AppointmentAlreadyCanceledException(String errorCode, String errorMessage, Throwable rootCause) { - super(errorCode, errorMessage, rootCause); - } - - public AppointmentAlreadyCanceledException() { - super(); - } -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/AppointmentBookingFailedException.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/AppointmentBookingFailedException.java deleted file mode 100644 index 40d09d262f9..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/AppointmentBookingFailedException.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.mosip.preregistration.booking.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.preregistration.core.common.dto.MainResponseDTO; -import lombok.Getter; - -/** - * @author M1046129 - * - */ - -@Getter -public class AppointmentBookingFailedException extends BaseUncheckedException { - - /** - * - */ - private static final long serialVersionUID = 5135952690225019228L; - private MainResponseDTO mainResponseDTO; - - public AppointmentBookingFailedException(String msg) { - super("", msg); - } - - public AppointmentBookingFailedException(String msg, Throwable cause) { - super("", msg, cause); - } - - public AppointmentBookingFailedException(String errorCode, String errorMessage) { - super(errorCode, errorMessage, null); - } - - public AppointmentBookingFailedException(String errorCode, String errorMessage,MainResponseDTO response) { - super(errorCode, errorMessage, null); - this.mainResponseDTO=response; - } - - public AppointmentBookingFailedException(String errorCode, String errorMessage, Throwable rootCause) { - super(errorCode, errorMessage, rootCause); - } - - public AppointmentBookingFailedException() { - super(); - } -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/AppointmentCannotBeBookedException.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/AppointmentCannotBeBookedException.java deleted file mode 100644 index 5cbf94b75fd..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/AppointmentCannotBeBookedException.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.mosip.preregistration.booking.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.preregistration.core.common.dto.MainResponseDTO; -import lombok.Getter; - -/** - * @author M1046129 - * - */ - -@Getter -public class AppointmentCannotBeBookedException extends BaseUncheckedException { - - /** - * - */ - private static final long serialVersionUID = 5135952690225019228L; - private MainResponseDTO mainResponseDTO; - - public AppointmentCannotBeBookedException(String msg) { - super("", msg); - } - - public AppointmentCannotBeBookedException(String msg, Throwable cause) { - super("", msg, cause); - } - - public AppointmentCannotBeBookedException(String errorCode, String errorMessage) { - super(errorCode, errorMessage, null); - } - - public AppointmentCannotBeBookedException(String errorCode, String errorMessage,MainResponseDTO response) { - super(errorCode, errorMessage, null); - this.mainResponseDTO=response; - } - - public AppointmentCannotBeBookedException(String errorCode, String errorMessage, Throwable rootCause) { - super(errorCode, errorMessage, rootCause); - } - - public AppointmentCannotBeBookedException() { - super(); - } -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/AppointmentCannotBeCanceledException.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/AppointmentCannotBeCanceledException.java deleted file mode 100644 index 30e648329e9..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/AppointmentCannotBeCanceledException.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.mosip.preregistration.booking.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.preregistration.core.common.dto.MainResponseDTO; -import lombok.Getter; - -/** - * @author M1046129 - * - */ - -@Getter -public class AppointmentCannotBeCanceledException extends BaseUncheckedException { - - /** - * - */ - private static final long serialVersionUID = 5135952690225019228L; - private MainResponseDTO mainResponseDTO; - - public AppointmentCannotBeCanceledException(String msg) { - super("", msg); - } - - public AppointmentCannotBeCanceledException(String msg, Throwable cause) { - super("", msg, cause); - } - - public AppointmentCannotBeCanceledException(String errorCode, String errorMessage) { - super(errorCode, errorMessage, null); - } - - public AppointmentCannotBeCanceledException(String errorCode, String errorMessage,MainResponseDTO response) { - super(errorCode, errorMessage, null); - this.mainResponseDTO=response; - } - - public AppointmentCannotBeCanceledException(String errorCode, String errorMessage, Throwable rootCause) { - super(errorCode, errorMessage, rootCause); - } - - public AppointmentCannotBeCanceledException() { - super(); - } -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/AppointmentReBookingFailedException.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/AppointmentReBookingFailedException.java deleted file mode 100644 index b8d7f3e5fb0..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/AppointmentReBookingFailedException.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.mosip.preregistration.booking.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.preregistration.core.common.dto.MainResponseDTO; -import lombok.Getter; - -/** - * @author M1046129 - * - */ - -@Getter -public class AppointmentReBookingFailedException extends BaseUncheckedException { - - /** - * - */ - private static final long serialVersionUID = 5135952690225019228L; - private MainResponseDTO mainResponseDTO; - - public AppointmentReBookingFailedException(String msg) { - super("", msg); - } - - public AppointmentReBookingFailedException(String msg, Throwable cause) { - super("", msg, cause); - } - - public AppointmentReBookingFailedException(String errorCode, String errorMessage) { - super(errorCode, errorMessage, null); - } - - public AppointmentReBookingFailedException(String errorCode, String errorMessage,MainResponseDTO response) { - super(errorCode, errorMessage, null); - this.mainResponseDTO=response; - } - - public AppointmentReBookingFailedException(String errorCode, String errorMessage, Throwable rootCause) { - super(errorCode, errorMessage, rootCause); - } - - public AppointmentReBookingFailedException() { - super(); - } -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/AvailabilityTableNotAccessableException.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/AvailabilityTableNotAccessableException.java deleted file mode 100644 index ae484c258ba..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/AvailabilityTableNotAccessableException.java +++ /dev/null @@ -1,44 +0,0 @@ -package io.mosip.preregistration.booking.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.preregistration.core.common.dto.MainResponseDTO; -import lombok.Getter; - -/** - * Thrown when the availability table cannot be read. - */ -@Getter -public class AvailabilityTableNotAccessableException extends BaseUncheckedException { - - /** - * - */ - private static final long serialVersionUID = 5135952690225019228L; - /** MOSIP envelope copied onto the error response. */ - private MainResponseDTO mainResponseDTO; - - public AvailabilityTableNotAccessableException(String msg) { - super("", msg); - } - - public AvailabilityTableNotAccessableException(String msg, Throwable cause) { - super("", msg, cause); - } - - public AvailabilityTableNotAccessableException(String errorCode, String errorMessage) { - super(errorCode, errorMessage, null); - } - - public AvailabilityTableNotAccessableException(String errorCode, String errorMessage,MainResponseDTO response) { - super(errorCode, errorMessage, null); - this.mainResponseDTO=response; - } - - public AvailabilityTableNotAccessableException(String errorCode, String errorMessage, Throwable rootCause) { - super(errorCode, errorMessage, rootCause); - } - - public AvailabilityTableNotAccessableException() { - super(); - } -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/AvailabilityUpdationFailedException.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/AvailabilityUpdationFailedException.java deleted file mode 100644 index 16c157691a4..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/AvailabilityUpdationFailedException.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.mosip.preregistration.booking.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.preregistration.core.common.dto.MainResponseDTO; -import lombok.Getter; - -/** - * Thrown when incrementing/decrementing slot availability fails. - */ -@Getter -public class AvailabilityUpdationFailedException extends BaseUncheckedException{ - - - /** - * - */ - private static final long serialVersionUID = -8740121632422570371L; - /** MOSIP envelope copied onto the error response. */ - private MainResponseDTO mainResponseDTO; - - public AvailabilityUpdationFailedException(String msg) { - super("", msg); - } - - public AvailabilityUpdationFailedException(String msg, Throwable cause) { - super("", msg, cause); - } - - public AvailabilityUpdationFailedException(String errorCode, String errorMessage) { - super(errorCode, errorMessage, null); - } - - public AvailabilityUpdationFailedException(String errorCode, String errorMessage,MainResponseDTO response) { - super(errorCode, errorMessage, null); - this.mainResponseDTO=response; - } - - public AvailabilityUpdationFailedException(String errorCode, String errorMessage, Throwable rootCause) { - super(errorCode, errorMessage, rootCause); - } - - public AvailabilityUpdationFailedException() { - super(); - } -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/AvailablityNotFoundException.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/AvailablityNotFoundException.java deleted file mode 100644 index 29dc958e398..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/AvailablityNotFoundException.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.mosip.preregistration.booking.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.preregistration.core.common.dto.MainResponseDTO; -import lombok.Getter; - -/** - * @author M1046129 - * - */ - -@Getter -public class AvailablityNotFoundException extends BaseUncheckedException { - - /** - * - */ - private static final long serialVersionUID = 5135952690225019228L; - private MainResponseDTO mainResponseDTO; - - public AvailablityNotFoundException(String msg) { - super("", msg); - } - - public AvailablityNotFoundException(String msg, Throwable cause) { - super("", msg, cause); - } - - public AvailablityNotFoundException(String errorCode, String errorMessage) { - super(errorCode, errorMessage, null); - } - - public AvailablityNotFoundException(String errorCode, String errorMessage,MainResponseDTO respone) { - super(errorCode, errorMessage, null); - this.mainResponseDTO=respone; - } - - public AvailablityNotFoundException(String errorCode, String errorMessage, Throwable rootCause) { - super(errorCode, errorMessage, rootCause); - } - - public AvailablityNotFoundException() { - super(); - } -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/BookingDataNotFoundException.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/BookingDataNotFoundException.java deleted file mode 100644 index eda11b4b93c..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/BookingDataNotFoundException.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.mosip.preregistration.booking.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.preregistration.core.common.dto.MainResponseDTO; -import lombok.Getter; - -/** - * @author M1046129 - * - */ - -@Getter -public class BookingDataNotFoundException extends BaseUncheckedException { - - /** - * - */ - private static final long serialVersionUID = 5135952690225019228L; - private MainResponseDTO mainResponseDTO; - - public BookingDataNotFoundException(String msg) { - super("", msg); - } - - public BookingDataNotFoundException(String msg, Throwable cause) { - super("", msg, cause); - } - - public BookingDataNotFoundException(String errorCode, String errorMessage) { - super(errorCode, errorMessage, null); - } - - public BookingDataNotFoundException(String errorCode, String errorMessage,MainResponseDTO response) { - super(errorCode, errorMessage, null); - this.mainResponseDTO=response; - } - - public BookingDataNotFoundException(String errorCode, String errorMessage, Throwable rootCause) { - super(errorCode, errorMessage, rootCause); - } - - public BookingDataNotFoundException() { - super(); - } -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/BookingDateNotSeletectedException.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/BookingDateNotSeletectedException.java deleted file mode 100644 index 3dc67b754b8..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/BookingDateNotSeletectedException.java +++ /dev/null @@ -1,44 +0,0 @@ -package io.mosip.preregistration.booking.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.preregistration.core.common.dto.MainResponseDTO; -import lombok.Getter; - -/** - * @author M1046129 - * - */ -@Getter -public class BookingDateNotSeletectedException extends BaseUncheckedException { - - /** - * - */ - private static final long serialVersionUID = -8090038321393006576L; - private MainResponseDTO mainResponseDTO; - - public BookingDateNotSeletectedException(String msg) { - super("", msg); - } - - public BookingDateNotSeletectedException(String msg, Throwable cause) { - super("", msg, cause); - } - - public BookingDateNotSeletectedException(String errorCode, String errorMessage) { - super(errorCode, errorMessage, null); - } - - public BookingDateNotSeletectedException(String errorCode, String errorMessage,MainResponseDTO response) { - super(errorCode, errorMessage, null); - this.mainResponseDTO=response; - } - - public BookingDateNotSeletectedException(String errorCode, String errorMessage, Throwable rootCause) { - super(errorCode, errorMessage, rootCause); - } - - public BookingDateNotSeletectedException() { - super(); - } -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/BookingPreIdNotFoundException.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/BookingPreIdNotFoundException.java deleted file mode 100644 index b7484558931..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/BookingPreIdNotFoundException.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.mosip.preregistration.booking.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.preregistration.core.common.dto.MainResponseDTO; -import lombok.Getter; - -/** - * @author M1046129 - * - */ - -@Getter -public class BookingPreIdNotFoundException extends BaseUncheckedException { - - /** - * - */ - private static final long serialVersionUID = -8090038321393006576L; - private MainResponseDTO mainResponseDTO; - - public BookingPreIdNotFoundException(String msg) { - super("", msg); - } - - public BookingPreIdNotFoundException(String msg, Throwable cause) { - super("", msg, cause); - } - - public BookingPreIdNotFoundException(String errorCode, String errorMessage) { - super(errorCode, errorMessage, null); - } - - public BookingPreIdNotFoundException(String errorCode, String errorMessage,MainResponseDTO response) { - super(errorCode, errorMessage, null); - this.mainResponseDTO=response; - } - - public BookingPreIdNotFoundException(String errorCode, String errorMessage, Throwable rootCause) { - super(errorCode, errorMessage, rootCause); - } - - public BookingPreIdNotFoundException() { - super(); - } -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/BookingRegistrationCenterIdNotFoundException.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/BookingRegistrationCenterIdNotFoundException.java deleted file mode 100644 index 1496857a17c..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/BookingRegistrationCenterIdNotFoundException.java +++ /dev/null @@ -1,42 +0,0 @@ -package io.mosip.preregistration.booking.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.preregistration.core.common.dto.MainResponseDTO; -import lombok.Getter; - -/** - * @author M1046129 - * - */ - -@Getter -public class BookingRegistrationCenterIdNotFoundException extends BaseUncheckedException { - - private static final long serialVersionUID = -5462747645675773416L; - private MainResponseDTO mainResponseDTO; - - public BookingRegistrationCenterIdNotFoundException(String msg) { - super("", msg); - } - - public BookingRegistrationCenterIdNotFoundException(String msg, Throwable cause) { - super("", msg, cause); - } - - public BookingRegistrationCenterIdNotFoundException(String errorCode, String errorMessage) { - super(errorCode, errorMessage, null); - } - - public BookingRegistrationCenterIdNotFoundException(String errorCode, String errorMessage,MainResponseDTO response) { - super(errorCode, errorMessage, null); - this.mainResponseDTO=response; - } - - public BookingRegistrationCenterIdNotFoundException(String errorCode, String errorMessage, Throwable rootCause) { - super(errorCode, errorMessage, rootCause); - } - - public BookingRegistrationCenterIdNotFoundException() { - super(); - } -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/BookingTimeSlotAlreadyBooked.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/BookingTimeSlotAlreadyBooked.java deleted file mode 100644 index df01548142c..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/BookingTimeSlotAlreadyBooked.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.mosip.preregistration.booking.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.preregistration.core.common.dto.MainResponseDTO; -import lombok.Getter; - -/** - * @author M1046129 - * - */ - -@Getter -public class BookingTimeSlotAlreadyBooked extends BaseUncheckedException { - - /** - * - */ - private static final long serialVersionUID = -7620811373366498697L; - private MainResponseDTO mainResponseDTO; - - public BookingTimeSlotAlreadyBooked(String msg) { - super("", msg); - } - - public BookingTimeSlotAlreadyBooked(String msg, Throwable cause) { - super("", msg, cause); - } - - public BookingTimeSlotAlreadyBooked(String errorCode, String errorMessage) { - super(errorCode, errorMessage, null); - } - - public BookingTimeSlotAlreadyBooked(String errorCode, String errorMessage,MainResponseDTO response) { - super(errorCode, errorMessage, null); - this.mainResponseDTO=response; - } - - public BookingTimeSlotAlreadyBooked(String errorCode, String errorMessage, Throwable rootCause) { - super(errorCode, errorMessage, rootCause); - } - - public BookingTimeSlotAlreadyBooked() { - super(); - } -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/BookingTimeSlotNotSeletectedException.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/BookingTimeSlotNotSeletectedException.java deleted file mode 100644 index ff677b7b6c3..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/BookingTimeSlotNotSeletectedException.java +++ /dev/null @@ -1,42 +0,0 @@ -package io.mosip.preregistration.booking.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.preregistration.core.common.dto.MainResponseDTO; -import lombok.Getter; - -/** - * @author M1046129 - * - */ - -@Getter -public class BookingTimeSlotNotSeletectedException extends BaseUncheckedException { - - private static final long serialVersionUID = -4543476272744645661L; - private MainResponseDTO mainResponseDTO; - - public BookingTimeSlotNotSeletectedException(String msg) { - super("", msg); - } - - public BookingTimeSlotNotSeletectedException(String msg, Throwable cause) { - super("", msg, cause); - } - - public BookingTimeSlotNotSeletectedException(String errorCode, String errorMessage) { - super(errorCode, errorMessage, null); - } - - public BookingTimeSlotNotSeletectedException(String errorCode, String errorMessage,MainResponseDTO response) { - super(errorCode, errorMessage, null); - this.mainResponseDTO=response; - } - - public BookingTimeSlotNotSeletectedException(String errorCode, String errorMessage, Throwable rootCause) { - super(errorCode, errorMessage, rootCause); - } - - public BookingTimeSlotNotSeletectedException() { - super(); - } -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/CancelAppointmentFailedException.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/CancelAppointmentFailedException.java deleted file mode 100644 index 79bc6f0bbe0..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/CancelAppointmentFailedException.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.mosip.preregistration.booking.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.preregistration.core.common.dto.MainResponseDTO; -import lombok.Getter; - -/** - * @author M1046129 - * - */ - -@Getter -public class CancelAppointmentFailedException extends BaseUncheckedException { - - /** - * - */ - private static final long serialVersionUID = 5135952690225019228L; - private MainResponseDTO mainResponseDTO; - - public CancelAppointmentFailedException(String msg) { - super("", msg); - } - - public CancelAppointmentFailedException(String msg, Throwable cause) { - super("", msg, cause); - } - - public CancelAppointmentFailedException(String errorCode, String errorMessage) { - super(errorCode, errorMessage, null); - } - - public CancelAppointmentFailedException(String errorCode, String errorMessage,MainResponseDTO response) { - super(errorCode, errorMessage, null); - this.mainResponseDTO=response; - } - - public CancelAppointmentFailedException(String errorCode, String errorMessage, Throwable rootCause) { - super(errorCode, errorMessage, rootCause); - } - - public CancelAppointmentFailedException() { - super(); - } -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/DemographicGetStatusException.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/DemographicGetStatusException.java deleted file mode 100644 index d2d99652861..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/DemographicGetStatusException.java +++ /dev/null @@ -1,43 +0,0 @@ -package io.mosip.preregistration.booking.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.preregistration.core.common.dto.MainResponseDTO; -import lombok.Getter; - -/** - * @author M1046129 - * - */ - -@Getter -public class DemographicGetStatusException extends BaseUncheckedException { - - private static final long serialVersionUID = 1L; - private MainResponseDTO mainResponseDTO; - - public DemographicGetStatusException(String msg) { - super("", msg); - } - - public DemographicGetStatusException(String msg, Throwable cause) { - super("", msg, cause); - } - - public DemographicGetStatusException(String errorCode, String errorMessage) { - super(errorCode, errorMessage, null); - } - - public DemographicGetStatusException(String errorCode, String errorMessage,MainResponseDTO response) { - super(errorCode, errorMessage, null); - this.mainResponseDTO=response; - } - - public DemographicGetStatusException(String errorCode, String errorMessage, Throwable rootCause) { - super(errorCode, errorMessage, rootCause); - } - - public DemographicGetStatusException() { - super(); - } - -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/DemographicStatusUpdationException.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/DemographicStatusUpdationException.java deleted file mode 100644 index 4f00c30188d..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/DemographicStatusUpdationException.java +++ /dev/null @@ -1,44 +0,0 @@ -package io.mosip.preregistration.booking.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.preregistration.core.common.dto.MainResponseDTO; -import lombok.Getter; - -/** - * @author M1046129 - * - */ - -@Getter -public class DemographicStatusUpdationException extends BaseUncheckedException { - - private static final long serialVersionUID = 1L; - private MainResponseDTO mainResponseDTO; - - public DemographicStatusUpdationException(String msg) { - super("", msg); - } - - public DemographicStatusUpdationException(String msg, Throwable cause) { - super("", msg, cause); - } - - public DemographicStatusUpdationException(String errorCode, String errorMessage) { - super(errorCode, errorMessage, null); - } - - public DemographicStatusUpdationException(String errorCode, String errorMessage,MainResponseDTO response) { - super(errorCode, errorMessage, null); - this.mainResponseDTO=response; - } - - public DemographicStatusUpdationException(String errorCode, String errorMessage, Throwable rootCause) { - super(errorCode, errorMessage, rootCause); - } - - public DemographicStatusUpdationException() { - super(); - } - - -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/DocumentNotFoundException.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/DocumentNotFoundException.java deleted file mode 100644 index b7db5849f8a..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/DocumentNotFoundException.java +++ /dev/null @@ -1,43 +0,0 @@ -package io.mosip.preregistration.booking.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.preregistration.core.common.dto.MainResponseDTO; -import lombok.Getter; - -/** - * @author M1046129 - * - */ - -@Getter -public class DocumentNotFoundException extends BaseUncheckedException { - - private static final long serialVersionUID = 1L; - private MainResponseDTO mainResponseDTO; - - public DocumentNotFoundException(String msg) { - super("", msg); - } - - public DocumentNotFoundException(String msg, Throwable cause) { - super("", msg, cause); - } - - public DocumentNotFoundException(String errorCode, String errorMessage) { - super(errorCode, errorMessage, null); - } - - public DocumentNotFoundException(String errorCode, String errorMessage,MainResponseDTO response) { - super(errorCode, errorMessage, null); - this.mainResponseDTO=response; - } - - public DocumentNotFoundException(String errorCode, String errorMessage, Throwable rootCause) { - super(errorCode, errorMessage, rootCause); - } - - public DocumentNotFoundException() { - super(); - } - -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/InvalidDateTimeFormatException.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/InvalidDateTimeFormatException.java deleted file mode 100644 index 96c6dcf4337..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/InvalidDateTimeFormatException.java +++ /dev/null @@ -1,46 +0,0 @@ -package io.mosip.preregistration.booking.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.preregistration.core.common.dto.MainResponseDTO; -import lombok.Getter; - -/** - * @author M1046129 - * - */ - -@Getter -public class InvalidDateTimeFormatException extends BaseUncheckedException { - - /** - * - */ - private static final long serialVersionUID = -2782261618399872549L; - private MainResponseDTO mainResponseDTO; - - public InvalidDateTimeFormatException(String msg) { - super("", msg); - } - - public InvalidDateTimeFormatException(String msg, Throwable cause) { - super("", msg, cause); - } - - public InvalidDateTimeFormatException(String errorCode, String errorMessage) { - super(errorCode, errorMessage, null); - } - - public InvalidDateTimeFormatException(String errorCode, String errorMessage,MainResponseDTO response) { - super(errorCode, errorMessage, null); - this.mainResponseDTO=response; - } - - public InvalidDateTimeFormatException(String errorCode, String errorMessage, Throwable rootCause,MainResponseDTO response) { - super(errorCode, errorMessage, rootCause); - this.mainResponseDTO=response; - } - - public InvalidDateTimeFormatException() { - super(); - } -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/JsonException.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/JsonException.java deleted file mode 100644 index f62b62af72f..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/JsonException.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.mosip.preregistration.booking.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.preregistration.core.common.dto.MainResponseDTO; -import lombok.Getter; - -/** - * Thrown when booking JSON cannot be parsed. - */ -@Getter -public class JsonException extends BaseUncheckedException { - - /** - * - */ - private static final long serialVersionUID = -2782261618399872549L; - /** MOSIP envelope copied onto the error response. */ - private MainResponseDTO mainResponseDTO; - - public JsonException(String msg) { - super("", msg); - } - - public JsonException(String msg, Throwable cause) { - super("", msg, cause); - } - - public JsonException(String errorCode, String errorMessage) { - super(errorCode, errorMessage, null); - } - - public JsonException(String errorCode, String errorMessage,MainResponseDTO response) { - super(errorCode, errorMessage, null); - this.mainResponseDTO=response; - } - - public JsonException(String errorCode, String errorMessage, Throwable rootCause) { - super(errorCode, errorMessage, rootCause); - } - - public JsonException() { - super(); - } - -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/OperationNotAllowedException.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/OperationNotAllowedException.java deleted file mode 100644 index cd223a8290d..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/OperationNotAllowedException.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright - * - */ -package io.mosip.preregistration.booking.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.preregistration.core.common.dto.MainResponseDTO; -import lombok.Getter; - -/** - * This class defines the OperationNotAllowedException - * - * @author Rajath KR - * @since 1.0.0 - * - */ - -@Getter -public class OperationNotAllowedException extends BaseUncheckedException { - /** The Constant serialVersionUID. */ - private static final long serialVersionUID = 1L; - private MainResponseDTO mainResponseDTO; - - /** - * @param errorMessage pass the error message - */ - public OperationNotAllowedException(String errorMessage) { - super("", errorMessage); - } - - /** - * @param errorCode pass the error code - * @param errorMessage pass the error message - */ - public OperationNotAllowedException(String errorCode, String errorMessage) { - super(errorCode, errorMessage, null); - } - - public OperationNotAllowedException(String errorCode, String errorMessage,MainResponseDTO response) { - super(errorCode, errorMessage, null); - this.mainResponseDTO=response; - } - - /** - * @param errorMessage pass the error message - * @param rootCause pass the cause - */ - public OperationNotAllowedException(String errorMessage, Throwable rootCause) { - super("", errorMessage, rootCause); - } - - /** - * @param errorCode pass the error code - * @param errorMessage pass the error message - * @param rootCause pass the cause - */ - public OperationNotAllowedException(String errorCode, String errorMessage, Throwable rootCause) { - super(errorCode, errorMessage, rootCause); - } -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/RecordNotFoundException.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/RecordNotFoundException.java deleted file mode 100644 index 00eb1c42085..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/RecordNotFoundException.java +++ /dev/null @@ -1,41 +0,0 @@ -package io.mosip.preregistration.booking.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.preregistration.core.common.dto.MainResponseDTO; -import lombok.Getter; - - -@Getter -public class RecordNotFoundException extends BaseUncheckedException { - - /** - * - */ - private static final long serialVersionUID = -2782261618399872549L; - private MainResponseDTO mainResponseDTO; - - public RecordNotFoundException(String msg) { - super("", msg); - } - - public RecordNotFoundException(String msg, Throwable cause) { - super("", msg, cause); - } - - public RecordNotFoundException(String errorCode, String errorMessage) { - super(errorCode, errorMessage, null); - } - - public RecordNotFoundException(String errorCode, String errorMessage,MainResponseDTO response) { - super(errorCode, errorMessage, null); - this.mainResponseDTO=response; - } - - public RecordNotFoundException(String errorCode, String errorMessage, Throwable rootCause) { - super(errorCode, errorMessage, rootCause); - } - - public RecordNotFoundException() { - super(); - } -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/TimeSpanException.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/TimeSpanException.java deleted file mode 100644 index 9159874c6f3..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/TimeSpanException.java +++ /dev/null @@ -1,47 +0,0 @@ -package io.mosip.preregistration.booking.exception; - -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.preregistration.core.common.dto.MainResponseDTO; -import lombok.Getter; - -/** - * Thrown when an appointment is requested outside the allowed time span. - */ -@Getter -public class TimeSpanException extends BaseUncheckedException{ - - /** - * - */ - private static final long serialVersionUID = -5676105896729083192L; - /** MOSIP envelope copied onto the error response. */ - private MainResponseDTO mainResponseDTO; - - /** - * @param msg error text - */ - public TimeSpanException(String msg) { - super("", msg); - } - - public TimeSpanException(String msg, Throwable cause) { - super("", msg, cause); - } - - public TimeSpanException(String errorCode, String errorMessage) { - super(errorCode, errorMessage, null); - } - - public TimeSpanException(String errorCode, String errorMessage,MainResponseDTO response) { - super(errorCode, errorMessage, null); - this.mainResponseDTO=response; - } - - public TimeSpanException(String errorCode, String errorMessage, Throwable rootCause) { - super(errorCode, errorMessage, rootCause); - } - - public TimeSpanException() { - super(); - } -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/util/BookingExceptionCatcher.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/util/BookingExceptionCatcher.java deleted file mode 100644 index a02a120eea9..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/util/BookingExceptionCatcher.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Copyright - * - */ -package io.mosip.preregistration.booking.exception.util; - -import java.time.DateTimeException; -import java.time.format.DateTimeParseException; - -import com.fasterxml.jackson.core.JsonProcessingException; - -import io.mosip.kernel.core.dataaccess.exception.DataAccessLayerException; -import io.mosip.kernel.core.exception.BaseCheckedException; -import io.mosip.kernel.core.exception.BaseUncheckedException; -import io.mosip.kernel.core.exception.ParseException; -import io.mosip.preregistration.booking.errorcodes.ErrorCodes; -import io.mosip.preregistration.booking.errorcodes.ErrorMessages; -import io.mosip.preregistration.booking.exception.AppointmentAlreadyCanceledException; -import io.mosip.preregistration.booking.exception.AppointmentBookingFailedException; -import io.mosip.preregistration.booking.exception.AppointmentCannotBeBookedException; -import io.mosip.preregistration.booking.exception.AppointmentCannotBeCanceledException; -import io.mosip.preregistration.booking.exception.AppointmentReBookingFailedException; -import io.mosip.preregistration.booking.exception.AvailablityNotFoundException; -import io.mosip.preregistration.booking.exception.BookingDataNotFoundException; -import io.mosip.preregistration.booking.exception.BookingDateNotSeletectedException; -import io.mosip.preregistration.booking.exception.BookingPreIdNotFoundException; -import io.mosip.preregistration.booking.exception.BookingRegistrationCenterIdNotFoundException; -import io.mosip.preregistration.booking.exception.BookingTimeSlotAlreadyBooked; -import io.mosip.preregistration.booking.exception.BookingTimeSlotNotSeletectedException; -import io.mosip.preregistration.booking.exception.CancelAppointmentFailedException; -import io.mosip.preregistration.booking.exception.DemographicGetStatusException; -import io.mosip.preregistration.booking.exception.DemographicStatusUpdationException; -import io.mosip.preregistration.booking.exception.DocumentNotFoundException; -import io.mosip.preregistration.booking.exception.InvalidDateTimeFormatException; -import io.mosip.preregistration.booking.exception.JsonException; -import io.mosip.preregistration.booking.exception.OperationNotAllowedException; -import io.mosip.preregistration.booking.exception.RecordNotFoundException; -import io.mosip.preregistration.booking.exception.TimeSpanException; -import io.mosip.preregistration.core.common.dto.MainResponseDTO; -import io.mosip.preregistration.core.exception.AppointmentBookException; -import io.mosip.preregistration.core.exception.AppointmentCancelException; -import io.mosip.preregistration.core.exception.AppointmentReBookException; -import io.mosip.preregistration.core.exception.InvalidRequestException; -import io.mosip.preregistration.core.exception.InvalidRequestParameterException; -import io.mosip.preregistration.core.exception.NotificationException; -import io.mosip.preregistration.core.exception.PreRegistrationException; -import io.mosip.preregistration.core.exception.RecordFailedToDeleteException; -import io.mosip.preregistration.core.exception.RestCallException; -import io.mosip.preregistration.core.exception.TableNotAccessibleException; - -/** - * This class is used to catch the exceptions that occur while Booking - * - * @author Kishan Rathore - * @author Jagadishwari - * @author Ravi C. Balaji - * @since 1.0.0 - * - */ -public class BookingExceptionCatcher { - - /** - * Method to handle the respective exceptions - * - * @param ex - * pass the exception - */ - public void handle(Exception ex, MainResponseDTO mainResponseDTO) { - if (ex instanceof RecordNotFoundException) { - throw new RecordNotFoundException(((RecordNotFoundException) ex).getErrorCode(), - ((RecordNotFoundException) ex).getErrorText(), mainResponseDTO); - } else if (ex instanceof InvalidRequestParameterException) { - throw new InvalidRequestParameterException(((InvalidRequestParameterException) ex).getErrorCode(), - ((InvalidRequestParameterException) ex).getErrorText(), mainResponseDTO); - } else if (ex instanceof DateTimeException || ex instanceof java.time.format.DateTimeParseException - || ex instanceof InvalidDateTimeFormatException || ex instanceof java.text.ParseException) { - throw new InvalidDateTimeFormatException( - ((InvalidDateTimeFormatException)ex).getErrorCode(), - ((InvalidDateTimeFormatException)ex).getErrorText(), - mainResponseDTO); - } else if (ex instanceof ParseException) { - throw new ParseException(io.mosip.preregistration.core.errorcodes.ErrorCodes.PRG_CORE_REQ_019.toString(), - io.mosip.preregistration.core.errorcodes.ErrorMessages.INVALID_DATE_TIME_FORMAT.getMessage()); - } else if (ex instanceof DocumentNotFoundException) { - throw new DocumentNotFoundException(((DocumentNotFoundException) ex).getErrorCode(), - ((DocumentNotFoundException) ex).getErrorText(), mainResponseDTO); - } else if (ex instanceof DataAccessLayerException) { - - throw new TableNotAccessibleException(((DataAccessLayerException) ex).getErrorCode(), - ((DataAccessLayerException) ex).getErrorText(), mainResponseDTO); - } else if (ex instanceof BookingDataNotFoundException) { - throw new BookingDataNotFoundException(((BookingDataNotFoundException) ex).getErrorCode(), - ((BookingDataNotFoundException) ex).getErrorText(), mainResponseDTO); - } else if (ex instanceof AppointmentBookingFailedException) { - throw new AppointmentBookingFailedException(((AppointmentBookingFailedException) ex).getErrorCode(), - ((AppointmentBookingFailedException) ex).getErrorText(), mainResponseDTO); - } else if (ex instanceof BookingTimeSlotAlreadyBooked) { - throw new BookingTimeSlotAlreadyBooked(((BookingTimeSlotAlreadyBooked) ex).getErrorCode(), - ((BookingTimeSlotAlreadyBooked) ex).getErrorText(), mainResponseDTO); - } else if (ex instanceof AppointmentReBookingFailedException) { - throw new AppointmentReBookingFailedException(((AppointmentReBookingFailedException) ex).getErrorCode(), - ((AppointmentReBookingFailedException) ex).getErrorText(), mainResponseDTO); - } else if (ex instanceof BookingPreIdNotFoundException) { - throw new BookingPreIdNotFoundException(((BookingPreIdNotFoundException) ex).getErrorCode(), - ((BookingPreIdNotFoundException) ex).getErrorText(), mainResponseDTO); - } else if (ex instanceof BookingRegistrationCenterIdNotFoundException) { - throw new BookingRegistrationCenterIdNotFoundException( - ((BookingRegistrationCenterIdNotFoundException) ex).getErrorCode(), - ((BookingRegistrationCenterIdNotFoundException) ex).getErrorText(), mainResponseDTO); - } else if (ex instanceof BookingTimeSlotNotSeletectedException) { - throw new BookingTimeSlotNotSeletectedException(((BookingTimeSlotNotSeletectedException) ex).getErrorCode(), - ((BookingTimeSlotNotSeletectedException) ex).getErrorText(), mainResponseDTO); - } else if (ex instanceof BookingDateNotSeletectedException) { - throw new BookingDateNotSeletectedException(((BookingDateNotSeletectedException) ex).getErrorCode(), - ((BookingDateNotSeletectedException) ex).getErrorText(), mainResponseDTO); - } else if (ex instanceof AppointmentCannotBeBookedException) { - throw new AppointmentCannotBeBookedException(((AppointmentCannotBeBookedException) ex).getErrorCode(), - ((AppointmentCannotBeBookedException) ex).getErrorText(), mainResponseDTO); - } else if (ex instanceof CancelAppointmentFailedException) { - throw new CancelAppointmentFailedException(((CancelAppointmentFailedException) ex).getErrorCode(), - ((CancelAppointmentFailedException) ex).getErrorText(), mainResponseDTO); - } else if (ex instanceof AvailablityNotFoundException) { - throw new AvailablityNotFoundException(((AvailablityNotFoundException) ex).getErrorCode(), - ((AvailablityNotFoundException) ex).getErrorText(), mainResponseDTO); - } else if (ex instanceof AppointmentAlreadyCanceledException) { - throw new AppointmentAlreadyCanceledException(((AppointmentAlreadyCanceledException) ex).getErrorCode(), - ((AppointmentAlreadyCanceledException) ex).getErrorText(), mainResponseDTO); - } else if (ex instanceof AppointmentCannotBeCanceledException) { - throw new AppointmentCannotBeCanceledException(((AppointmentCannotBeCanceledException) ex).getErrorCode(), - ((AppointmentCannotBeCanceledException) ex).getErrorText(), mainResponseDTO); - } else if (ex instanceof DemographicGetStatusException) { - throw new DemographicGetStatusException(((DemographicGetStatusException) ex).getErrorCode(), - ((DemographicGetStatusException) ex).getErrorText(), mainResponseDTO); - } else if (ex instanceof AppointmentBookException) { - throw new AppointmentBookException(((AppointmentBookException) ex).getErrorCode(), - ((AppointmentBookException) ex).getErrorText(), mainResponseDTO); - } else if (ex instanceof AppointmentCancelException) { - throw new AppointmentCancelException(((AppointmentCancelException) ex).getErrorCode(), - ((AppointmentCancelException) ex).getErrorText(), mainResponseDTO); - } else if (ex instanceof AppointmentReBookException) { - throw new AppointmentReBookException(((AppointmentReBookException) ex).getErrorCode(), - ((AppointmentReBookException) ex).getErrorText(), mainResponseDTO); - } else if (ex instanceof TimeSpanException) { - throw new TimeSpanException(((TimeSpanException) ex).getErrorCode(), - ((TimeSpanException) ex).getErrorText(), mainResponseDTO); - } else if (ex instanceof RecordFailedToDeleteException) { - throw new RecordFailedToDeleteException(((RecordFailedToDeleteException) ex).getErrorCode(), - ((RecordFailedToDeleteException) ex).getErrorText(), mainResponseDTO); - } else if (ex instanceof OperationNotAllowedException) { - throw new OperationNotAllowedException(((OperationNotAllowedException) ex).getErrorCode(), - ((OperationNotAllowedException) ex).getErrorText(), mainResponseDTO); - } else if (ex instanceof DemographicStatusUpdationException) { - throw new DemographicStatusUpdationException(((DemographicStatusUpdationException) ex).getErrorCode(), - ((DemographicStatusUpdationException) ex).getErrorText(), mainResponseDTO); - } else if (ex instanceof DateTimeParseException) { - throw new InvalidDateTimeFormatException(ErrorCodes.PRG_BOOK_RCI_031.getCode(), - ErrorMessages.INVALID_BOOKING_DATE_TIME.getMessage(), mainResponseDTO); - } else if (ex instanceof TableNotAccessibleException) { - throw new TableNotAccessibleException(((TableNotAccessibleException) ex).getErrorCode(), - ((TableNotAccessibleException) ex).getErrorText(), mainResponseDTO); - } else if (ex instanceof RestCallException) { - throw new RestCallException(((RestCallException) ex).getErrorCode(), - ((RestCallException) ex).getErrorText(), mainResponseDTO); - } else if (ex instanceof NotificationException) { - throw new NotificationException(((NotificationException) ex).getValidationErrorList(), mainResponseDTO); - } else if (ex instanceof JsonProcessingException) { - throw new JsonException(ErrorCodes.PRG_BOOK_RCI_034.getCode(), - ErrorMessages.JSON_PROCESSING_EXCEPTION.getMessage(), mainResponseDTO); - } else if (ex instanceof InvalidRequestException) { - throw new InvalidRequestException(((InvalidRequestException) ex).getErrorCode(), - ((InvalidRequestException) ex).getErrorText(), mainResponseDTO); - } else { - if (ex instanceof BaseUncheckedException) { - throw new PreRegistrationException(((BaseUncheckedException) ex).getErrorCode(), - ((BaseUncheckedException) ex).getErrorText(), mainResponseDTO); - } else if (ex instanceof BaseCheckedException) { - throw new PreRegistrationException(((BaseCheckedException) ex).getErrorCode(), - ((BaseCheckedException) ex).getErrorText(), mainResponseDTO); - } - } - - } - -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/util/BookingExceptionHandler.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/util/BookingExceptionHandler.java deleted file mode 100644 index d1e09cb15eb..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/exception/util/BookingExceptionHandler.java +++ /dev/null @@ -1,481 +0,0 @@ -/* - * Copyright - * - */ -package io.mosip.preregistration.booking.exception.util; - -import java.io.IOException; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Map; - -import jakarta.annotation.Resource; -import jakarta.servlet.http.HttpServletRequest; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.env.Environment; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.http.converter.HttpMessageNotReadableException; -import org.springframework.security.access.AccessDeniedException; -import org.springframework.validation.FieldError; -import org.springframework.web.bind.MethodArgumentNotValidException; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.RestControllerAdvice; -import org.springframework.web.context.request.WebRequest; -import org.springframework.web.util.ContentCachingRequestWrapper; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; - -import io.mosip.kernel.core.exception.ParseException; -import io.mosip.kernel.core.exception.ServiceError; -import io.mosip.kernel.core.util.DateUtils2; -import io.mosip.kernel.core.util.EmptyCheckUtils; -import io.mosip.preregistration.booking.exception.AppointmentAlreadyCanceledException; -import io.mosip.preregistration.booking.exception.AppointmentBookingFailedException; -import io.mosip.preregistration.booking.exception.AppointmentCannotBeBookedException; -import io.mosip.preregistration.booking.exception.AppointmentCannotBeCanceledException; -import io.mosip.preregistration.booking.exception.AppointmentReBookingFailedException; -import io.mosip.preregistration.booking.exception.AvailabilityTableNotAccessableException; -import io.mosip.preregistration.booking.exception.AvailablityNotFoundException; -import io.mosip.preregistration.booking.exception.BookingDataNotFoundException; -import io.mosip.preregistration.booking.exception.BookingDateNotSeletectedException; -import io.mosip.preregistration.booking.exception.BookingPreIdNotFoundException; -import io.mosip.preregistration.booking.exception.BookingRegistrationCenterIdNotFoundException; -import io.mosip.preregistration.booking.exception.BookingTimeSlotAlreadyBooked; -import io.mosip.preregistration.booking.exception.BookingTimeSlotNotSeletectedException; -import io.mosip.preregistration.booking.exception.CancelAppointmentFailedException; -import io.mosip.preregistration.booking.exception.DemographicGetStatusException; -import io.mosip.preregistration.booking.exception.DemographicStatusUpdationException; -import io.mosip.preregistration.booking.exception.DocumentNotFoundException; -import io.mosip.preregistration.booking.exception.InvalidDateTimeFormatException; -import io.mosip.preregistration.booking.exception.JsonException; -import io.mosip.preregistration.booking.exception.OperationNotAllowedException; -import io.mosip.preregistration.booking.exception.RecordNotFoundException; -import io.mosip.preregistration.booking.exception.TimeSpanException; -import io.mosip.preregistration.core.common.dto.ExceptionJSONInfoDTO; -import io.mosip.preregistration.core.common.dto.MainResponseDTO; -import io.mosip.preregistration.core.common.dto.ResponseWrapper; -import io.mosip.preregistration.core.exception.InvalidRequestException; -import io.mosip.preregistration.core.exception.InvalidRequestParameterException; -import io.mosip.preregistration.core.exception.MasterDataNotAvailableException; -import io.mosip.preregistration.core.exception.NotificationException; -import io.mosip.preregistration.core.exception.PreRegistrationException; -import io.mosip.preregistration.core.exception.RecordFailedToDeleteException; -import io.mosip.preregistration.core.exception.RestCallException; -import io.mosip.preregistration.core.exception.TableNotAccessibleException; -import io.mosip.preregistration.core.util.GenericUtil; - -/** - * Exception Handler for Booking application. - * - * @author Kishan Rathore - * @author Jagadishwari - * @since 1.0.0 - * - */ -@RestControllerAdvice -public class BookingExceptionHandler { - - /** The Environment. */ - @Autowired - protected Environment env; - - /** The id. */ - @Resource - protected Map id; - - @Value("${mosip.utc-datetime-pattern}") - private String utcDateTimePattern; - - @Value("${version}") - String versionUrl; - - @Value("${mosip.preregistration.booking.exception.id}") - String idUrl; - - /** - * @param e - * @param request - * @return error response - */ - @ExceptionHandler(DemographicStatusUpdationException.class) - public ResponseEntity> updateStatusException(final DemographicStatusUpdationException e) { - return GenericUtil.errorResponse(e, e.getMainResponseDTO()); - } - - /** - * @param e - * @param request - * @return error response - */ - @ExceptionHandler(AvailabilityTableNotAccessableException.class) - public ResponseEntity> availabilityTableNotAccessableException( - final AvailabilityTableNotAccessableException e) { - return GenericUtil.errorResponse(e, e.getMainResponseDTO()); - } - - /** - * @param e - * @param request - * @return error response - */ - @ExceptionHandler(DemographicGetStatusException.class) - public ResponseEntity> getStatusException(final DemographicGetStatusException e) { - return GenericUtil.errorResponse(e, e.getMainResponseDTO()); - } - - /** - * @param e - * @param request - * @return error response - */ - @ExceptionHandler(MasterDataNotAvailableException.class) - public ResponseEntity> masterDataNotAvailableException(final MasterDataNotAvailableException e) { - return GenericUtil.errorResponse(e, e.getMainResponseDTO()); - } - - /** - * @param e - * @param request - * @return error response - */ - @ExceptionHandler(RestCallException.class) - public ResponseEntity> databaseerror(final RestCallException e) { - return GenericUtil.errorResponse(e, e.getMainResponseDTO()); - } - - /** - * @param e - * @param request - * @return error response - */ - @ExceptionHandler(BookingTimeSlotNotSeletectedException.class) - public ResponseEntity> timeSlotNotSelected(final BookingTimeSlotNotSeletectedException e) { - return GenericUtil.errorResponse(e, e.getMainResponseDTO()); - } - - /** - * @param e - * @param request - * @return error response - */ - @ExceptionHandler(AppointmentCannotBeBookedException.class) - public ResponseEntity> timeSlotNotSelected(final AppointmentCannotBeBookedException e) { - return GenericUtil.errorResponse(e, e.getMainResponseDTO()); - - } - - /** - * @param e - * @param request - * @return error response - */ - @ExceptionHandler(BookingPreIdNotFoundException.class) - public ResponseEntity> preIdNotFound(final BookingPreIdNotFoundException e) { - return GenericUtil.errorResponse(e, e.getMainResponseDTO()); - } - - /** - * @param e - * @param request - * @return error response - */ - @ExceptionHandler(BookingRegistrationCenterIdNotFoundException.class) - public ResponseEntity> regCenterNotFound(final BookingRegistrationCenterIdNotFoundException e) { - return GenericUtil.errorResponse(e, e.getMainResponseDTO()); - } - - /** - * @param e - * @param request - * @return error response - */ - @ExceptionHandler(InvalidDateTimeFormatException.class) - public ResponseEntity> invalidDateTimeException(final InvalidDateTimeFormatException e) { - return GenericUtil.errorResponse(e, e.getMainResponseDTO()); - } - - /** - * @param e - * @param request - * @return error response - */ - @ExceptionHandler(BookingTimeSlotAlreadyBooked.class) - public ResponseEntity> timeSlotAlreadyBooked(final BookingTimeSlotAlreadyBooked e) { - return GenericUtil.errorResponse(e, e.getMainResponseDTO()); - } - - /** - * @param e - * @param request - * @return error response - */ - @ExceptionHandler(BookingDateNotSeletectedException.class) - public ResponseEntity> bookingDateNotSelected(final BookingDateNotSeletectedException e) { - return GenericUtil.errorResponse(e, e.getMainResponseDTO()); - } - - /** - * @param e - * @param request - * @return error response - */ - @ExceptionHandler(InvalidRequestParameterException.class) - public ResponseEntity> bookingDateNotSelected(final InvalidRequestParameterException e) { - MainResponseDTO errorRes = e.getMainResponseDto(); - errorRes.setId(id.get(e.getOperation())); - errorRes.setVersion(env.getProperty("version")); - errorRes.setErrors(e.getExptionList()); - errorRes.setResponsetime(GenericUtil.getCurrentResponseTime()); - return new ResponseEntity<>(errorRes, HttpStatus.OK); - } - - /** - * @param e - * @param request - * @return error response - */ - @ExceptionHandler(BookingDataNotFoundException.class) - public ResponseEntity> bookingDataNotFound(final BookingDataNotFoundException e) { - return GenericUtil.errorResponse(e, e.getMainResponseDTO()); - } - - /** - * @param e - * @param request - * @return error response - */ - @ExceptionHandler(RecordNotFoundException.class) - public ResponseEntity> recordNotFound(final RecordNotFoundException e) { - return GenericUtil.errorResponse(e, e.getMainResponseDTO()); - } - - /** - * @param e - * @param request - * @return error response - */ - @ExceptionHandler(AppointmentAlreadyCanceledException.class) - public ResponseEntity> appointmentAlreadyCanceledException( - final AppointmentAlreadyCanceledException e) { - return GenericUtil.errorResponse(e, e.getMainResponseDTO()); - } - - /** - * @param e - * @param request - * @return error response - */ - @ExceptionHandler(AppointmentCannotBeCanceledException.class) - public ResponseEntity> appointmentCanNotCanceledException( - final AppointmentCannotBeCanceledException e) { - return GenericUtil.errorResponse(e, e.getMainResponseDTO()); - } - - /** - * @param e - * @param request - * @return error response - */ - - @ExceptionHandler(CancelAppointmentFailedException.class) - public ResponseEntity> appointmentCancelFailedException( - final CancelAppointmentFailedException e) { - return GenericUtil.errorResponse(e, e.getMainResponseDTO()); - } - - /** - * @param e - * @param request - * @return error response - */ - - @ExceptionHandler(AppointmentReBookingFailedException.class) - public ResponseEntity> appointmentReBookingFailedException( - final AppointmentReBookingFailedException e) { - return GenericUtil.errorResponse(e, e.getMainResponseDTO()); - } - - /** - * @param e - * @param request - * @return error response - */ - - @ExceptionHandler(DocumentNotFoundException.class) - public ResponseEntity> documentNotFound(final DocumentNotFoundException e) { - return GenericUtil.errorResponse(e, e.getMainResponseDTO()); - } - - /** - * @param e - * @param request - * @return error response - */ - - @ExceptionHandler(AvailablityNotFoundException.class) - public ResponseEntity> availablityNotFound(final AvailablityNotFoundException e) { - return GenericUtil.errorResponse(e, e.getMainResponseDTO()); - } - - /** - * @param e - * @param request - * @return error response - */ - - @ExceptionHandler(TableNotAccessibleException.class) - - public ResponseEntity> tablenotAccessible(final TableNotAccessibleException e) { - return GenericUtil.errorResponse(e, e.getMainResposneDTO()); - } - - /** - * @param e - * @param request - * @return error response - */ - - @ExceptionHandler(AppointmentBookingFailedException.class) - public ResponseEntity> appointmentBookingFailed(final AppointmentBookingFailedException e) { - return GenericUtil.errorResponse(e, e.getMainResponseDTO()); - } - - @ExceptionHandler(TimeSpanException.class) - public ResponseEntity> timeSpanException(final TimeSpanException e) { - return GenericUtil.errorResponse(e, e.getMainResponseDTO()); - - } - - @ExceptionHandler(RecordFailedToDeleteException.class) - public ResponseEntity> recordFailedToDeleteException(final RecordFailedToDeleteException e) { - return GenericUtil.errorResponse(e, e.getMainResponseDTO()); - - } - - @ExceptionHandler(OperationNotAllowedException.class) - public ResponseEntity> operationNotAllowedException(final OperationNotAllowedException e) { - return GenericUtil.errorResponse(e, e.getMainResponseDTO()); - - } - - @ExceptionHandler(JsonException.class) - public ResponseEntity> jsonException(final JsonException e) { - return GenericUtil.errorResponse(e, e.getMainResponseDTO()); - - } - - @ExceptionHandler(ParseException.class) - public ResponseEntity> parseException(final ParseException e) { - ExceptionJSONInfoDTO errorDetails = new ExceptionJSONInfoDTO(e.getErrorCode(), e.getErrorText()); - MainResponseDTO errorRes = new MainResponseDTO<>(); - List errorList = new ArrayList<>(); - errorList.add(errorDetails); - errorRes.setErrors(errorList); - errorRes.setId(idUrl); - errorRes.setVersion(versionUrl); - errorRes.setResponsetime(DateUtils2.formatDate(new Date(), utcDateTimePattern)); - - return new ResponseEntity<>(errorRes, HttpStatus.OK); - - } - - @ExceptionHandler(MethodArgumentNotValidException.class) - public ResponseEntity> methodArgumentNotValidException( - final HttpServletRequest httpServletRequest, final MethodArgumentNotValidException e) throws IOException { - ResponseWrapper errorResponse = setErrors(httpServletRequest); - final List fieldErrors = e.getBindingResult().getFieldErrors(); - fieldErrors.forEach(x -> { - ServiceError error = new ServiceError( - io.mosip.preregistration.core.errorcodes.ErrorCodes.PRG_CORE_REQ_015.getCode(), - x.getField() + ": " + x.getDefaultMessage()); - errorResponse.getErrors().add(error); - }); - return new ResponseEntity<>(errorResponse, HttpStatus.OK); - } - - @ExceptionHandler(HttpMessageNotReadableException.class) - public ResponseEntity> onHttpMessageNotReadable( - final HttpServletRequest httpServletRequest, final HttpMessageNotReadableException e) throws IOException { - ResponseWrapper errorResponse = setErrors(httpServletRequest); - ServiceError error = new ServiceError( - io.mosip.preregistration.core.errorcodes.ErrorCodes.PRG_CORE_REQ_015.getCode(), e.getMessage()); - errorResponse.getErrors().add(error); - return new ResponseEntity<>(errorResponse, HttpStatus.OK); - } - - @ExceptionHandler(value = { Exception.class, RuntimeException.class }) - public ResponseEntity> defaultErrorHandler( - final HttpServletRequest httpServletRequest, Exception e) throws IOException { - ResponseWrapper errorResponse = setErrors(httpServletRequest); - ServiceError error = new ServiceError( - io.mosip.preregistration.core.errorcodes.ErrorCodes.PRG_CORE_REQ_016.getCode(), e.getMessage()); - errorResponse.getErrors().add(error); - return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR); - } - - @ExceptionHandler(value = AccessDeniedException.class) - public ResponseEntity> AccessDeniedExceptionHandler(final AccessDeniedException e) { - MainResponseDTO errorRes = new MainResponseDTO<>(); - List errorList = new ArrayList<>(); - ExceptionJSONInfoDTO errorDetails = new ExceptionJSONInfoDTO("KER-401", "Authentication Failed"); - errorList.add(errorDetails); - errorRes.setErrors(errorList); - errorRes.setResponsetime(DateUtils2.formatDate(new Date(), utcDateTimePattern)); - return new ResponseEntity<>(errorRes, HttpStatus.UNAUTHORIZED); - } - - @Autowired - private ObjectMapper objectMapper; - - private ResponseWrapper setErrors(HttpServletRequest httpServletRequest) throws IOException { - ResponseWrapper responseWrapper = new ResponseWrapper<>(); - responseWrapper.setResponsetime(LocalDateTime.now(ZoneId.of("UTC"))); - String requestBody = null; - if (httpServletRequest instanceof ContentCachingRequestWrapper) { - requestBody = new String(((ContentCachingRequestWrapper) httpServletRequest).getContentAsByteArray()); - } - if (EmptyCheckUtils.isNullEmpty(requestBody)) { - return responseWrapper; - } - objectMapper.registerModule(new JavaTimeModule()); - JsonNode reqNode = objectMapper.readTree(requestBody); - responseWrapper.setId(reqNode.path("id").asText()); - responseWrapper.setVersion(reqNode.path("version").asText()); - return responseWrapper; - } - - @ExceptionHandler(NotificationException.class) - public ResponseEntity> authServiceException(final NotificationException e, WebRequest request) { - List errorList = new ArrayList<>(); - e.getValidationErrorList().stream().forEach(serviceError -> errorList - .add(new ExceptionJSONInfoDTO(serviceError.getErrorCode(), serviceError.getMessage()))); - MainResponseDTO errorRes = e.getMainResponseDTO(); - errorRes.setErrors(errorList); - errorRes.setResponsetime(GenericUtil.getCurrentResponseTime()); - return new ResponseEntity<>(errorRes, HttpStatus.OK); - } - - @ExceptionHandler(PreRegistrationException.class) - public ResponseEntity> commonException(final PreRegistrationException e) { - return GenericUtil.errorResponse(e, e.getMainresponseDTO()); - } - - /** - * - * @param e - * @return - */ - @ExceptionHandler(InvalidRequestException.class) - public ResponseEntity> invalidRequestException(final InvalidRequestException e) { - return GenericUtil.errorResponse(e, e.getMainResponseDto()); - } - -} \ No newline at end of file diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/repository/BookingAvailabilityRepository.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/repository/BookingAvailabilityRepository.java deleted file mode 100644 index c3227ab9666..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/repository/BookingAvailabilityRepository.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Copyright - * - */ -package io.mosip.preregistration.booking.repository; - -import java.time.LocalDate; -import java.time.LocalTime; -import java.util.List; - -import jakarta.transaction.Transactional; -import jakarta.persistence.LockModeType; - -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.jpa.repository.Lock; -import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; - -import io.mosip.kernel.core.dataaccess.spi.repository.BaseRepository; -import io.mosip.preregistration.booking.entity.AvailibityEntity; - -/** - * This repository interface is used to define the JPA methods for Booking application. - * - * @author Kishan Rathore - * @author Jagadishwari - * @author Ravi C. Balaji - * @since 1.0.0 - * - */ -@Repository("bookingAvailabilityRepository") -@Transactional -public interface BookingAvailabilityRepository extends BaseRepository { - - - /** - * @param Registration center id - * @param Registration date - * @return List AvailibityEntity based registration id and registration date. - */ - public List findByRegcntrIdAndRegDateOrderByFromTimeAsc(String regcntrId, LocalDate regDate); - - /** - * @param regcntrId - * @param fromDate - * @param toDate - * @return List of LocalDate based on date - */ - public List findDate(@Param("regcntrId") String regcntrId, @Param("fromDate") LocalDate fromDate, - @Param("toDate") LocalDate toDate); - - /** - * @param slot_from_time - * @param slot_to_time - * @param reg_date - * @param regcntr_id - * @return Availability entity - */ - @Deprecated(forRemoval = true) - public AvailibityEntity findByFromTimeAndToTimeAndRegDateAndRegcntrId( - @Param("slot_from_time") LocalTime slotFromTime, @Param("slot_to_time") LocalTime slotToTime, - @Param("availability_date") LocalDate regDate, @Param("regcntr_id") String regcntrd); - - /** - * @param reg_date - * @param regcntr_id - * @param slot_from_time - * @param slot_to_time - * @return Availability entity - */ - public AvailibityEntity findByRegDateAndRegcntrIdAndFromTimeAndToTime( - @Param("availability_date") LocalDate regDate, - @Param("regcntr_id") String regcntrd, - @Param("slot_from_time") LocalTime slotFromTime, @Param("slot_to_time") LocalTime slotToTime ); - - - /** - * @param reg_date - * @param regcntr_id - * @param slot_from_time - * @param slot_to_time - * @return Availability entity - * This API performs a database lock. Use it with care. - */ - @Lock(LockModeType.PESSIMISTIC_WRITE) - public AvailibityEntity findFirstByRegDateAndRegcntrIdAndFromTimeAndToTime( - @Param("availability_date") LocalDate regDate, - @Param("regcntr_id") String regcntrd, - @Param("slot_from_time") LocalTime slotFromTime, @Param("slot_to_time") LocalTime slotToTime ); - - - /** - * - * @param regDate - * @return list of available date - */ - @Query("SELECT DISTINCT e.regDate FROM AvailibityEntity e WHERE e.regDate>= ?1") - public List findAvaialableDate(LocalDate regDate); - - public List findByRegcntrId(String regCenterId); - - /** - * - * @param regDate - * @return list of available date - */ - @Query("SELECT DISTINCT e.regcntrId FROM AvailibityEntity e WHERE e.regDate>= ?1") - public List findAvaialableRegCenter(LocalDate regDate); - - /** - * - * @param regDate - * @param regcntrId - * @return list of available date - */ - @Query("SELECT DISTINCT e.regDate FROM AvailibityEntity e WHERE e.regDate>= ?1 and e.regcntrId=?2") - public List findAvaialableDate(LocalDate regDate, String regcntrId); - - - /** - * - * @param regDate - * @param regcntrId - * @return list of AvailibityEntity - */ - @Query("SELECT DISTINCT e FROM AvailibityEntity e WHERE e.regDate= ?1 and e.regcntrId=?2") - public List findAvaialableSlots(LocalDate regDate, String regcntrId); - - - /** - * - * @param regDate - * @param regcntrId - * @return deleted number of slots - */ - public int deleteByRegcntrIdAndRegDate( String regcntrId ,LocalDate regDate); - - /** - * - * @param regDate - * @return list of regcntrId - */ - public int deleteByRegcntrIdAndRegDateGreaterThanEqual(String regcntrId, LocalDate regDate); - - /** - * @param Registration center id - * @param Registration startDate - * @param Registration endDate - * @return List AvailibityEntity based registration id and registration date. - */ - public List findByRegcntrIdAndRegDateGreaterThanEqualAndRegDateLessThanEqualOrderByFromTimeAsc(String regcntrId, LocalDate starteDate,LocalDate endDate); - -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/repository/DemographicRepository.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/repository/DemographicRepository.java deleted file mode 100644 index 9a08d1965da..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/repository/DemographicRepository.java +++ /dev/null @@ -1,24 +0,0 @@ -package io.mosip.preregistration.booking.repository; - -import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; - -import io.mosip.kernel.core.dataaccess.spi.repository.BaseRepository; -import io.mosip.preregistration.core.common.entity.DemographicEntity; - -/** - * @author Kishan Rathore - * @since 1.0.0 - * - */ -@Repository("demographicRepository") -public interface DemographicRepository extends BaseRepository { - - /** - * @param preRegId - * pass preRegId - * @return preregistration date for a pre-id - */ - public DemographicEntity findBypreRegistrationId(@Param("preRegId") String preRegId); - -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/repository/RegistrationBookingRepository.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/repository/RegistrationBookingRepository.java deleted file mode 100644 index b13acdd690a..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/repository/RegistrationBookingRepository.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright - * - */ -package io.mosip.preregistration.booking.repository; - -import java.time.LocalDate; -import java.util.List; - -import org.springframework.data.jpa.repository.Modifying; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; -import org.springframework.transaction.annotation.Transactional; - -import io.mosip.kernel.core.dataaccess.spi.repository.BaseRepository; -import io.mosip.preregistration.core.common.entity.RegistrationBookingEntity; - -/** - * This repository interface is used to define the JPA methods for Booking - * application. - * - * @author Kishan Rathore - * @author Jagadishwari - * @author Ravi C. Balaji - * @since 1.0.0 - * - */ -@Repository("registrationBookingRepository") -@Transactional -public interface RegistrationBookingRepository extends BaseRepository { - - public static final String preIdQuery = "SELECT u FROM RegistrationBookingEntity u WHERE u.preregistrationId = ?1"; - public static final String deletePreIdQuery = "delete from RegistrationBookingEntity u where u.preregistrationId = ?1"; - public static final String getPreIdQuery = "select u from RegistrationBookingEntity u where u.registrationCenterId=?3 and u.regDate between ?1 and ?2"; - - @Query(preIdQuery) - RegistrationBookingEntity getDemographicEntityPreRegistrationId(@Param("preRegId") String preRegId); - - /** - * @param registrationCenterId - * @param statusCode - * @return List RegistrationBookingEntity based on Registration center id and - * status code - */ - public List findByRegistrationCenterId(@Param("regcntr_id") String registrationCenterId); - - @Query(preIdQuery) - public List findByDemographicEntityPreRegistrationId(String preId); - - @Transactional - @Modifying - @Query(deletePreIdQuery) - public int deleteByDemographicEntityPreRegistrationId(String preregistrationId); - - /** - * @param start - * pass startTime - * @param end - * pass endTime - * @return list of booked preregistration data between start and end date - */ - @Query(getPreIdQuery) - public List findByRegDateBetweenAndRegistrationCenterId(LocalDate start, LocalDate end, - String regCenterId); - - public List findByRegistrationCenterIdAndRegDate(String registrationCenterId, - LocalDate regDate); - - @Query("SELECT e FROM RegistrationBookingEntity e WHERE e.registrationCenterId= ?1 and e.regDate>=?2") - public List findByRegId(String registrationCenterId, LocalDate regDate); - -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/repository/impl/BookingDAO.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/repository/impl/BookingDAO.java deleted file mode 100644 index c28217554a5..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/repository/impl/BookingDAO.java +++ /dev/null @@ -1,468 +0,0 @@ -/* - * Copyright - * - */ -package io.mosip.preregistration.booking.repository.impl; - -import java.time.LocalDate; -import java.time.LocalTime; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.stereotype.Component; - -import org.springframework.transaction.annotation.Propagation; -import org.springframework.transaction.annotation.Transactional; - -import io.mosip.kernel.core.dataaccess.exception.DataAccessLayerException; -import io.mosip.preregistration.booking.dto.SlotTimeDto; -import io.mosip.preregistration.booking.entity.AvailibityEntity; -import io.mosip.preregistration.booking.errorcodes.ErrorCodes; -import io.mosip.preregistration.booking.errorcodes.ErrorMessages; -import io.mosip.preregistration.booking.exception.AvailabilityUpdationFailedException; -import io.mosip.preregistration.booking.exception.AvailablityNotFoundException; -import io.mosip.preregistration.booking.exception.BookingDataNotFoundException; -import io.mosip.preregistration.booking.exception.RecordNotFoundException; -import io.mosip.preregistration.booking.repository.BookingAvailabilityRepository; -import io.mosip.preregistration.booking.repository.DemographicRepository; -import io.mosip.preregistration.booking.repository.RegistrationBookingRepository; -import io.mosip.preregistration.core.common.entity.RegistrationBookingEntity; -import io.mosip.preregistration.core.exception.InvalidRequestParameterException; -import io.mosip.preregistration.core.exception.RecordFailedToDeleteException; -import io.mosip.preregistration.core.exception.TableNotAccessibleException; - -/** - * This repository class is used to implement the JPA methods for Booking - * application. - * - * @author Kishan Rathore - * @since 1.0.0 - * - */ -@Component -public class BookingDAO { - - /** Autowired reference for {@link #bookingRepository}. */ - @Autowired - @Qualifier("bookingAvailabilityRepository") - private BookingAvailabilityRepository bookingAvailabilityRepository; - - /** Autowired reference for {@link #registrationBookingRepository}. */ - @Autowired - @Qualifier("registrationBookingRepository") - private RegistrationBookingRepository registrationBookingRepository; - - @Autowired - @Qualifier("demographicRepository") - private DemographicRepository demographicRepository; - - /** - * @param Registration center id - * @param Registration date - * @return List AvailibityEntity based registration id and registration date. - */ - public List availability(String regcntrId, LocalDate regDate) { - List availabilityList = null; - try { - availabilityList = bookingAvailabilityRepository.findByRegcntrIdAndRegDateOrderByFromTimeAsc(regcntrId, - regDate); - } catch (DataAccessLayerException e) { - throw new AvailablityNotFoundException(ErrorCodes.PRG_BOOK_RCI_016.getCode(), - ErrorMessages.AVAILABILITY_TABLE_NOT_ACCESSABLE.getMessage()); - } - return availabilityList; - - } - - /** - * @param regcntrId - * @param fromDate - * @param toDate - * @return List of Local date - */ - public List findDate(String regcntrId, LocalDate fromDate, LocalDate toDate) { - List localDatList = null; - try { - localDatList = bookingAvailabilityRepository.findDate(regcntrId, fromDate, toDate); - } catch (DataAccessLayerException e) { - throw new TableNotAccessibleException(ErrorCodes.PRG_BOOK_RCI_016.getCode(), - ErrorMessages.AVAILABILITY_TABLE_NOT_ACCESSABLE.getMessage()); - } - return localDatList; - } - - /** - * @param slotFromTime - * @param slotToTime - * @param regDate - * @param regcntrd - * @return Availibity Entity based on FromTime, ToTime, RegDate and RegcntrId. - */ - @Deprecated(forRemoval = true) - public AvailibityEntity findByFromTimeAndToTimeAndRegDateAndRegcntrId(LocalTime slotFromTime, LocalTime slotToTime, - LocalDate regDate, String regcntrd) { - AvailibityEntity entity = null; - try { - entity = bookingAvailabilityRepository.findByFromTimeAndToTimeAndRegDateAndRegcntrId(slotFromTime, - slotToTime, regDate, regcntrd); - if (entity == null) { - - throw new AvailablityNotFoundException(ErrorCodes.PRG_BOOK_RCI_002.getCode(), - ErrorMessages.AVAILABILITY_NOT_FOUND_FOR_THE_SELECTED_TIME.getMessage()); - } - - } catch (DataAccessLayerException e) { - throw new TableNotAccessibleException(ErrorCodes.PRG_BOOK_RCI_016.getCode(), - ErrorMessages.AVAILABILITY_TABLE_NOT_ACCESSABLE.getMessage()); - } - return entity; - } - - /** - * @param regDate - * @param regcntrd - * @param slotFromTime - * @param slotToTime - * @return Availibity Entity based on FromTime, ToTime, RegDate and RegcntrId. - */ - public AvailibityEntity findByRegDateAndRegcntrIdAndFromTimeAndToTime(LocalDate regDate, String regcntrd, - LocalTime slotFromTime, LocalTime slotToTime) { - AvailibityEntity entity = null; - try { - entity = bookingAvailabilityRepository.findByRegDateAndRegcntrIdAndFromTimeAndToTime(regDate, regcntrd, - slotFromTime, slotToTime); - if (entity == null) { - - throw new AvailablityNotFoundException(ErrorCodes.PRG_BOOK_RCI_002.getCode(), - ErrorMessages.AVAILABILITY_NOT_FOUND_FOR_THE_SELECTED_TIME.getMessage()); - } - - } catch (DataAccessLayerException e) { - throw new TableNotAccessibleException(ErrorCodes.PRG_BOOK_RCI_016.getCode(), - ErrorMessages.AVAILABILITY_TABLE_NOT_ACCESSABLE.getMessage()); - } - return entity; - } - - /** - * @param slotFromTime - * @param slotToTime - * @param regDate - * @param regcntrd - * @return Availibity Entity based on FromTime, ToTime, RegDate and RegcntrId. - */ - @Transactional(propagation = Propagation.MANDATORY) - public AvailibityEntity findFirstByRegDateAndRegcntrIdAndFromTimeAndToTime(LocalDate regDate, String regcntrd, - LocalTime slotFromTime, LocalTime slotToTime) { - AvailibityEntity entity = null; - try { - entity = bookingAvailabilityRepository.findFirstByRegDateAndRegcntrIdAndFromTimeAndToTime(regDate, regcntrd, - slotFromTime, slotToTime); - if (entity == null) { - - throw new AvailablityNotFoundException(ErrorCodes.PRG_BOOK_RCI_002.getCode(), - ErrorMessages.AVAILABILITY_NOT_FOUND_FOR_THE_SELECTED_TIME.getMessage()); - } - - } catch (DataAccessLayerException e) { - throw new TableNotAccessibleException(ErrorCodes.PRG_BOOK_RCI_016.getCode(), - ErrorMessages.AVAILABILITY_TABLE_NOT_ACCESSABLE.getMessage()); - } - return entity; - } - - /** - * This method find entity for status other then CANCEL. - * - * @param preregistrationId - * @param statusCode - * @return RegistrationBookingEntity based on Pre registration id and status - * code. - */ - public RegistrationBookingEntity findByPreRegistrationId(String preregistrationId) { - RegistrationBookingEntity entity = null; - try { - entity = registrationBookingRepository.getDemographicEntityPreRegistrationId(preregistrationId); - if (entity == null) { - throw new BookingDataNotFoundException(ErrorCodes.PRG_BOOK_RCI_013.getCode(), - ErrorMessages.BOOKING_DATA_NOT_FOUND.getMessage()); - } - } catch (DataAccessLayerException e) { - throw new TableNotAccessibleException(ErrorCodes.PRG_BOOK_RCI_016.getCode(), - ErrorMessages.BOOKING_TABLE_NOT_ACCESSIBLE.getMessage()); - } - return entity; - } - - /** - * @param availibityEntity - * @return AvailibityEntity - */ - public AvailibityEntity updateAvailibityEntity(AvailibityEntity availibityEntity) { - AvailibityEntity entity = null; - try { - entity = bookingAvailabilityRepository.update(availibityEntity); - if (entity == null) { - throw new AvailabilityUpdationFailedException(ErrorCodes.PRG_BOOK_RCI_024.getCode(), - ErrorMessages.AVAILABILITY_UPDATE_FAILED.getMessage()); - } - } catch (DataAccessLayerException e) { - throw new TableNotAccessibleException(ErrorCodes.PRG_BOOK_RCI_016.getCode(), - ErrorMessages.AVAILABILITY_TABLE_NOT_ACCESSABLE.getMessage()); - } - return entity; - } - - /** - * @param bookingEntity - * @return RegistrationBookingEntity - */ - public RegistrationBookingEntity saveRegistrationEntityForBooking(RegistrationBookingEntity bookingEntity) { - RegistrationBookingEntity entity = null; - try { - entity = registrationBookingRepository.save(bookingEntity); - } catch (DataAccessLayerException e) { - throw new TableNotAccessibleException(ErrorCodes.PRG_BOOK_RCI_016.getCode(), - ErrorMessages.BOOKING_TABLE_NOT_ACCESSIBLE.getMessage()); - } - return entity; - } - - /** - * @param regcntrId - * @param regDate - * @return List of AvailibityEntity - */ - public List findByRegcntrIdAndRegDateOrderByFromTimeAsc(String regcntrId, LocalDate regDate) { - - List entityList = null; - try { - entityList = bookingAvailabilityRepository.findByRegcntrIdAndRegDateOrderByFromTimeAsc(regcntrId, regDate); - } catch (DataAccessLayerException e) { - throw new TableNotAccessibleException(ErrorCodes.PRG_BOOK_RCI_016.getCode(), - ErrorMessages.AVAILABILITY_TABLE_NOT_ACCESSABLE.getMessage()); - } - return entityList; - } - - public List findByPreregistrationId(String preId) { - List entityList = null; - try { - entityList = registrationBookingRepository.findByDemographicEntityPreRegistrationId(preId); - if (entityList.isEmpty()) { - throw new BookingDataNotFoundException(ErrorCodes.PRG_BOOK_RCI_013.getCode(), - ErrorMessages.BOOKING_DATA_NOT_FOUND.getMessage()); - } - } catch (DataAccessLayerException e) { - throw new TableNotAccessibleException(ErrorCodes.PRG_BOOK_RCI_016.getCode(), - ErrorMessages.BOOKING_TABLE_NOT_ACCESSIBLE.getMessage()); - } - return entityList; - - } - - public int deleteByPreRegistrationId(String preId) { - int count = registrationBookingRepository.deleteByDemographicEntityPreRegistrationId(preId); - if (count == 0) { - throw new RecordFailedToDeleteException(ErrorCodes.PRG_BOOK_RCI_028.getCode(), - ErrorMessages.FAILED_TO_DELETE_THE_PRE_REGISTRATION_RECORD.getMessage()); - } - return count; - } - - /** - * @param fromLocaldate - * @param toLocaldate - * @return - */ - public List findByBookingDateBetweenAndRegCenterId(LocalDate fromLocaldate, LocalDate toLocaldate, - String regCenterId, Map> idsWithSlotTime) { - List listOfPreIds = new ArrayList<>(); - try { - if (regCenterId != null && !regCenterId.isEmpty()) { - List entities = registrationBookingRepository - .findByRegDateBetweenAndRegistrationCenterId(fromLocaldate, toLocaldate, regCenterId); - if (entities != null && !entities.isEmpty()) { - for (RegistrationBookingEntity entity : entities) { - Map appointmentDate = new HashMap(); - appointmentDate.put(entity.getRegDate(), - new SlotTimeDto(entity.getSlotFromTime(), entity.getSlotToTime())); - idsWithSlotTime.put(entity.getPreregistrationId(), appointmentDate); - listOfPreIds.add(entity.getPreregistrationId()); - } - } else { - throw new BookingDataNotFoundException(ErrorCodes.PRG_BOOK_RCI_032.getCode(), - ErrorMessages.RECORD_NOT_FOUND_FOR_DATE_RANGE_AND_REG_CENTER_ID.getMessage()); - } - } else { - throw new InvalidRequestParameterException(ErrorCodes.PRG_BOOK_RCI_007.getCode(), - ErrorMessages.REGISTRATION_CENTER_ID_NOT_ENTERED.getMessage(), null); - } - } catch (DataAccessLayerException e) { - throw new BookingDataNotFoundException(ErrorCodes.PRG_BOOK_RCI_032.getCode(), - ErrorMessages.RECORD_NOT_FOUND_FOR_DATE_RANGE_AND_REG_CENTER_ID.getMessage()); - } - return listOfPreIds; - } - - public boolean findRegistrationCenterId(String regCenterId) { - List entityList = null; - try { - entityList = bookingAvailabilityRepository.findByRegcntrId(regCenterId); - if (entityList == null || entityList.isEmpty()) { - throw new RecordNotFoundException(ErrorCodes.PRG_BOOK_RCI_015.getCode(), - ErrorMessages.NO_TIME_SLOTS_ASSIGNED_TO_THAT_REG_CENTER.getMessage()); - } - return true; - - } catch (DataAccessLayerException e) { - throw new TableNotAccessibleException(ErrorCodes.PRG_BOOK_RCI_016.getCode(), - ErrorMessages.AVAILABILITY_TABLE_NOT_ACCESSABLE.getMessage()); - } - - } - - /** - * - * @param regDate - * @return list of regCenter - */ - public List findRegCenter(LocalDate regDate) { - List regCenterList = null; - try { - regCenterList = bookingAvailabilityRepository.findAvaialableRegCenter(regDate); - } catch (DataAccessLayerException e) { - throw new TableNotAccessibleException(ErrorCodes.PRG_BOOK_RCI_016.getCode(), - ErrorMessages.AVAILABILITY_TABLE_NOT_ACCESSABLE.getMessage()); - } - return regCenterList; - } - - /** - * - * @param regDate - * @param regID - * @return list of date - */ - public List findDistinctDate(LocalDate regDate, String regID) { - List localDatList = null; - try { - localDatList = bookingAvailabilityRepository.findAvaialableDate(regDate, regID); - } catch (DataAccessLayerException e) { - throw new TableNotAccessibleException(ErrorCodes.PRG_BOOK_RCI_016.getCode(), - ErrorMessages.AVAILABILITY_TABLE_NOT_ACCESSABLE.getMessage()); - } - return localDatList; - } - - /** - * - * @param regDate - * @param regID - * @return list of AvailibityEntity - */ - public List findSlots(LocalDate regDate, String regID) { - List localDatList = null; - try { - localDatList = bookingAvailabilityRepository.findAvaialableSlots(regDate, regID); - } catch (DataAccessLayerException e) { - throw new TableNotAccessibleException(ErrorCodes.PRG_BOOK_RCI_016.getCode(), - ErrorMessages.AVAILABILITY_TABLE_NOT_ACCESSABLE.getMessage()); - } - return localDatList; - } - - /** - * - * @param regId - * @param regDate - * @return number of deleted items - */ - public int deleteSlots(String regId, LocalDate regDate) { - int deletedSlots = 0; - try { - deletedSlots = bookingAvailabilityRepository.deleteByRegcntrIdAndRegDate(regId, regDate); - } catch (DataAccessLayerException e) { - throw new TableNotAccessibleException(ErrorCodes.PRG_BOOK_RCI_016.getCode(), - ErrorMessages.AVAILABILITY_TABLE_NOT_ACCESSABLE.getMessage()); - } - return deletedSlots; - } - - /** - * - * @param regId - * @param regDate - * @return list of RegistrationBookingEntity - */ - public List findAllPreIds(String regId, LocalDate regDate) { - List registrationBookingEntityList = null; - try { - registrationBookingEntityList = registrationBookingRepository.findByRegistrationCenterIdAndRegDate(regId, - regDate); - } catch (DataAccessLayerException e) { - throw new TableNotAccessibleException(ErrorCodes.PRG_BOOK_RCI_016.getCode(), - ErrorMessages.AVAILABILITY_TABLE_NOT_ACCESSABLE.getMessage()); - } - return registrationBookingEntityList; - } - - /** - * - * @param regId - * @param date - * @return list of RegistrationBookingEntity - */ - public List findAllPreIdsByregID(String regId, LocalDate date) { - List registrationBookingEntityList = null; - try { - registrationBookingEntityList = registrationBookingRepository.findByRegId(regId, date); - } catch (DataAccessLayerException e) { - throw new TableNotAccessibleException(ErrorCodes.PRG_BOOK_RCI_016.getCode(), - ErrorMessages.AVAILABILITY_TABLE_NOT_ACCESSABLE.getMessage()); - } - return registrationBookingEntityList; - } - - /** - * - * Aparam regId - * - * @param regDate - * @return number of deleted items - */ - public int deleteAllSlotsByRegId(String regId, LocalDate regDate) { - int deletedSlots = 0; - try { - deletedSlots = bookingAvailabilityRepository.deleteByRegcntrIdAndRegDateGreaterThanEqual(regId, regDate); - } catch (DataAccessLayerException e) { - throw new TableNotAccessibleException(ErrorCodes.PRG_BOOK_RCI_016.getCode(), - ErrorMessages.AVAILABILITY_TABLE_NOT_ACCESSABLE.getMessage()); - } - return deletedSlots; - } - - /** - * @param regcntrId - * @param regDate - * @return List of AvailibityEntity - */ - public List findAvailability(String regcntrId, LocalDate starteDate, LocalDate endDate) { - - List entityList = null; - try { - entityList = bookingAvailabilityRepository - .findByRegcntrIdAndRegDateGreaterThanEqualAndRegDateLessThanEqualOrderByFromTimeAsc(regcntrId, - starteDate, endDate); - } catch (DataAccessLayerException e) { - throw new TableNotAccessibleException(ErrorCodes.PRG_BOOK_RCI_016.getCode(), - ErrorMessages.AVAILABILITY_TABLE_NOT_ACCESSABLE.getMessage()); - } - return entityList; - } - -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/service/BookingService.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/service/BookingService.java deleted file mode 100644 index 8eca128283e..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/service/BookingService.java +++ /dev/null @@ -1,1103 +0,0 @@ -package io.mosip.preregistration.booking.service; - -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.LocalTime; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.TreeMap; -import java.util.stream.Collectors; - -import io.mosip.kernel.core.idvalidator.exception.InvalidIDException; -import jakarta.annotation.PostConstruct; - -import org.apache.commons.lang3.exception.ExceptionUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.stereotype.Component; -import org.springframework.transaction.annotation.Propagation; -import org.springframework.transaction.annotation.Transactional; - -import io.mosip.kernel.core.authmanager.authadapter.model.AuthUserDetails; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.preregistration.booking.codes.RequestCodes; -import io.mosip.preregistration.booking.dto.AvailabilityDto; -import io.mosip.preregistration.booking.dto.BookingDataByRegIdDto; -import io.mosip.preregistration.booking.dto.BookingRequestDTO; -import io.mosip.preregistration.booking.dto.BookingStatus; -import io.mosip.preregistration.booking.dto.BookingStatusDTO; -import io.mosip.preregistration.booking.dto.DateTimeDto; -import io.mosip.preregistration.booking.dto.MultiBookingRequest; -import io.mosip.preregistration.booking.dto.MultiBookingRequestDTO; -import io.mosip.preregistration.booking.dto.RegistrationCenterDto; -import io.mosip.preregistration.booking.dto.SlotTimeDto; -import io.mosip.preregistration.booking.entity.AvailibityEntity; -import io.mosip.preregistration.booking.errorcodes.ErrorCodes; -import io.mosip.preregistration.booking.errorcodes.ErrorMessages; -import io.mosip.preregistration.booking.exception.AvailablityNotFoundException; -import io.mosip.preregistration.booking.exception.DemographicGetStatusException; -import io.mosip.preregistration.booking.exception.RecordNotFoundException; -import io.mosip.preregistration.booking.exception.util.BookingExceptionCatcher; -import io.mosip.preregistration.booking.repository.impl.BookingDAO; -import io.mosip.preregistration.core.common.service.ApplicationIdentityMigrationService; -import io.mosip.preregistration.booking.service.util.BookingLock; -import io.mosip.preregistration.booking.service.util.BookingServiceUtil; -import io.mosip.preregistration.core.code.AuditLogVariables; -import io.mosip.preregistration.core.code.EventId; -import io.mosip.preregistration.core.code.EventName; -import io.mosip.preregistration.core.code.EventType; -import io.mosip.preregistration.core.code.StatusCodes; -import io.mosip.preregistration.core.common.dto.AuditRequestDto; -import io.mosip.preregistration.core.common.dto.BookingRegistrationDTO; -import io.mosip.preregistration.core.common.dto.CancelBookingResponseDTO; -import io.mosip.preregistration.core.common.dto.DeleteBookingDTO; -import io.mosip.preregistration.core.common.dto.MainRequestDTO; -import io.mosip.preregistration.core.common.dto.MainResponseDTO; -import io.mosip.preregistration.core.common.dto.PreRegIdsByRegCenterIdResponseDTO; -import io.mosip.preregistration.core.common.entity.RegistrationBookingEntity; -import io.mosip.preregistration.core.config.LoggerConfiguration; -import io.mosip.preregistration.core.util.AuditLogUtil; -import io.mosip.preregistration.core.util.UUIDGeneratorUtil; -import io.mosip.preregistration.core.util.ValidationUtil; - -/** - * This class provides the service implementation for Booking application. - * - * @author Kishan Rathore - * @author Jagadishwari - * @author Ravi C. Balaji - * @since 1.0.0 - * - */ -@Component -public class BookingService implements BookingServiceIntf { - - /** - * Autowired reference for {@link #serviceUtil} - */ - @Autowired - BookingServiceUtil serviceUtil; - - /** - * Best-effort canonical-identity backfill. - * - *

Propagation differs by call site, deliberately. The backfill is - * annotated {@code REQUIRED}, so in {@link #deleteBooking(String)} - which is - * {@code REQUIRES_NEW} - it joins that transaction and rolls back with it, - * while {@link #book(String, BookingRequestDTO)} and - * {@link #cancelBooking(String, boolean)} are intentionally non-transactional - * (see the note on their declarations, which predates this change), so there it - * runs in its own short transaction that commits independently of the booking. - * - *

Both are acceptable: the backfill is idempotent, converts only - * still-raw values, re-runs on the user's next activity, and is backstopped by - * the nightly identity reconciliation job. An independent commit is in fact the - * better outcome - the conversion survives even if the surrounding booking - * later fails. This class alters no transactional annotation. - */ - @Autowired - private ApplicationIdentityMigrationService applicationIdentityMigrationService; - - /** - * Reference for ${preregistration.availability.sync} from property file - */ - @Value("${preregistration.availability.sync}") - int syncDays; - - /** - * Reference for ${preregistration.availability.noOfDays} from property file - */ - @Value("${preregistration.availability.noOfDays}") - long displayDays; - - /** - * Reference for ${preregistration.booking.offset} from property file - */ - @Value("${preregistration.booking.offset}") - int availabilityOffset; - - @Autowired - private BookingDAO bookingDAO; - - @Autowired - private BookingLock bookingLock; - - @Value("${version}") - String versionUrl; - - @Value("${mosip.preregistration.booking.availability.sync.id}") - String idUrlSync; - - @Value("${mosip.preregistration.booking.id.book}") - String idUrlBookAppointment; - - @Value("${mosip.preregistration.booking.fetch.booking.id}") - String idUrlFetch; - - @Value("${mosip.preregistration.booking.cancel.id}") - String idUrlCancel; - - @Value("${mosip.preregistration.booking.delete.id}") - String idUrlDelete; - - @Value("${mosip.preregistration.booking.fetch.availability.id}") - String idUrlAvailability; - - @Value("${mosip.preregistration.booking.fetchPreidByDate.id}") - String idUrlBookingByDate; - - @Value("${mosip.preregistration.booking.availability.increase.id}") - String idUrlIncreaseAvailability; - - @Value("${mosip.preregistration.booking.availability.check.id}") - String idUrlCheckSlotAvailability; - - @Value("${mosip.preregistration.booking.delete.old.id}") - String idUrlDeleteOld; - - @Autowired - private ValidationUtil validationUtil; - - @PostConstruct - public void setupBookingService() { - - } - - private Logger log = LoggerConfiguration.logConfig(BookingService.class); - - @Autowired - private AuditLogUtil auditLogUtil; - - public AuthUserDetails authUserDetails() { - return (AuthUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); - } - - /* - * (non-Javadoc) - * - * @see io.mosip.preregistration.booking.serviceimpl.service.BookingServiceIntf# - * getAvailability(java.lang.String) - */ - @Override - public MainResponseDTO getAvailability(String regID) { - log.info("sessionId", "idType", "id", "In getAvailability method of Booking Service"); - MainResponseDTO response = new MainResponseDTO<>(); - response.setId(idUrlAvailability); - response.setVersion(versionUrl); - boolean isSaveSuccess = false; - - LocalDate endDate = LocalDate.now().plusDays(displayDays + availabilityOffset).minusDays(1); - LocalDate fromDate = LocalDate.now().plusDays(availabilityOffset); - AvailabilityDto availability = new AvailabilityDto(); - try { - if (serviceUtil.isValidRegCenter(regID)) { - int noOfHoliday = 0; - List availableEntity = bookingDAO.findAvailability(regID, fromDate, endDate); - List dateTimeList = new ArrayList<>(); - if (availableEntity == null) { - throw new RecordNotFoundException(ErrorCodes.PRG_BOOK_RCI_015.getCode(), - ErrorMessages.NO_TIME_SLOTS_ASSIGNED_TO_THAT_REG_CENTER.getMessage()); - } - - noOfHoliday = getSlot(dateTimeList, noOfHoliday, availableEntity); - while (noOfHoliday > 0) { - fromDate = endDate.plusDays(1); - endDate = endDate.plusDays(noOfHoliday); - availableEntity = bookingDAO.findAvailability(regID, fromDate, endDate); - if (availableEntity == null) { - log.info("sessionId", "idType", "id", - "There no slots available in case of holidays present in the given date range and no of Holidays is " - + noOfHoliday); - noOfHoliday = 0; - } else { - noOfHoliday = 0; - noOfHoliday = getSlot(dateTimeList, noOfHoliday, availableEntity); - } - } - availability.setCenterDetails(dateTimeList); - availability.setRegCenterId(regID); - isSaveSuccess = true; - } - } catch (Exception ex) { - log.debug("sessionId", "idType", "id", ExceptionUtils.getStackTrace(ex)); - log.error("sessionId", "idType", "id", "In getAvailability method of Booking Service- " + ex.getMessage()); - new BookingExceptionCatcher().handle(ex, response); - } finally { - if (isSaveSuccess) { - setAuditValues(EventId.PRE_401.toString(), EventName.RETRIEVE.toString(), EventType.BUSINESS.toString(), - "Availability retrieved successfully for booking", AuditLogVariables.MULTIPLE_ID.toString(), - authUserDetails().getUserId(), authUserDetails().getUsername(), regID); - } else { - setAuditValues(EventId.PRE_405.toString(), EventName.EXCEPTION.toString(), EventType.SYSTEM.toString(), - "Availability failed to get", AuditLogVariables.NO_ID.toString(), authUserDetails().getUserId(), - authUserDetails().getUsername(), regID); - } - } - response.setResponsetime(serviceUtil.getCurrentResponseTime()); - response.setResponse(availability); - return response; - } - - /** - * Retrieve number of holidays based on date Time, number of holidays and - * available slots - * - * @param dateTimeList - * @param noOfHoliday - * @param availableEntity - * @return noOfHoliday - */ - public int getSlot(List dateTimeList, int noOfHoliday, List availableEntity) { - Map> result = null; - result = availableEntity.stream().collect( - Collectors.groupingBy(AvailibityEntity::getRegDate, () -> new TreeMap<>(), Collectors.toList())); - for (Entry> entity : result.entrySet()) { - DateTimeDto dateTime = new DateTimeDto(); - noOfHoliday = noOfHoliday - + serviceUtil.slotSetter(entity.getKey(), dateTimeList, dateTime, entity.getValue()); - } - return noOfHoliday; - } - - /* - * (non-Javadoc) - * - * @see io.mosip.preregistration.booking.serviceimpl.service.BookingServiceIntf# - * bookAppointment(io.mosip.preregistration.core.common.dto.MainRequestDTO, - * java.lang.String) - */ - @Override - @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class) - public MainResponseDTO bookAppointment(MainRequestDTO bookingRequestDTOs, - String preRegistrationId) { - bookingLock.setDate(bookingRequestDTOs.getRequest().getRegDate()); - bookingLock.setRegistrationCenter(bookingRequestDTOs.getRequest().getRegDate()); - bookingLock.setTimeslot(bookingRequestDTOs.getRequest().getSlotFromTime()); - log.info("sessionId", "idType", "id", "In bookAppointment method of Booking Service"); - MainResponseDTO responseDTO = new MainResponseDTO<>(); - responseDTO.setId(idUrlBookAppointment); - responseDTO.setVersion(versionUrl); - boolean isSaveSuccess = false; - synchronized (bookingLock) { - - log.info("Sync block :", preRegistrationId, " Start", ""); - - BookingStatusDTO response = new BookingStatusDTO(); - try { - - BookingRequestDTO bookingRequestDTO = bookingRequestDTOs.getRequest(); - Map dateMap = new HashMap<>(); - dateMap.put(RequestCodes.REG_DATE.getCode(), bookingRequestDTO.getRegDate()); - dateMap.put(RequestCodes.FROM_SLOT_TIME.getCode(), bookingRequestDTO.getSlotFromTime()); - dateMap.put(RequestCodes.PRE_REGISTRAION_ID.getCode(), preRegistrationId); - if (serviceUtil.validateAppointmentDate(dateMap)) { - /* Getting Status From Demographic */ - String preRegStatusCode = serviceUtil.getApplicationBookingStatus(preRegistrationId); - log.info("preRegStatusCode : {}", preRegStatusCode); - - if (preRegStatusCode.equals(StatusCodes.APPLICATION_INCOMPLETE.getCode()) - || preRegStatusCode.equals(StatusCodes.PREFETCHED.getCode())) { - - if (preRegStatusCode.equals(StatusCodes.APPLICATION_INCOMPLETE.getCode())) { - throw new DemographicGetStatusException(ErrorCodes.PRG_BOOK_RCI_036.getCode(), - ErrorMessages.APPOINTMENT_CANNOT_BE_BOOKED_FOR_INCOMPLETE_APPLICATION.getMessage()); - } else { - throw new DemographicGetStatusException(ErrorCodes.PRG_BOOK_RCI_036.getCode(), - ErrorMessages.APPOINTMENT_CANNOT_BE_BOOKED_FOR_PREFETCHED_APPLICATION.getMessage()); - } - - } - - if (serviceUtil.mandatoryParameterCheck(preRegistrationId, bookingRequestDTO) - && serviceUtil.slotTimeValidCheck(preRegistrationId, bookingRequestDTO)) { - - /* Checking the availability of slots */ - checkSlotAvailability(bookingRequestDTO); - - if (preRegStatusCode.equals(StatusCodes.PENDING_APPOINTMENT.getCode()) - || preRegStatusCode.equals(StatusCodes.CANCELLED.getCode())) { - - /* Creating new booking */ - response = book(preRegistrationId, bookingRequestDTO); - - } else if (preRegStatusCode.equals(StatusCodes.BOOKED.getCode())) { - - /* Concatenating Booking date and slot from time */ - RegistrationBookingEntity bookingEntity = bookingDAO - .findByPreRegistrationId(preRegistrationId); - - System.out.println("Booking Entity " + bookingEntity); - - BookingRequestDTO oldBooking = new BookingRequestDTO(); - oldBooking.setRegDate(bookingEntity.getRegDate().toString()); - oldBooking.setRegistrationCenterId(bookingEntity.getRegistrationCenterId()); - oldBooking.setSlotFromTime(bookingEntity.getSlotFromTime().toString()); - oldBooking.setSlotToTime(bookingEntity.getSlotToTime().toString()); - - String str = bookingEntity.getRegDate() + " " + bookingEntity.getSlotFromTime(); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); - LocalDateTime bookedDateTime = LocalDateTime.parse(str, formatter); - - log.info("sessionId", "idType", "id", - "In bookAppointment method of Booking Service for booking Date Time- " - + bookedDateTime); - /* Time span check for re-book */ - serviceUtil.timeSpanCheckForRebook(bookedDateTime, bookingRequestDTOs.getRequesttime()); - - /* Deleting old booking */ - deleteOldBooking(preRegistrationId); - - /* Increase availability */ - increaseAvailability(oldBooking); - - /* Creating new booking */ - response = book(preRegistrationId, bookingRequestDTO); - - } else if (preRegStatusCode.equals(StatusCodes.EXPIRED.getCode())) { - - /* Deleting old booking */ - deleteOldBooking(preRegistrationId); - - /* Creating new booking */ - response = book(preRegistrationId, bookingRequestDTO); - } - - } - - } - isSaveSuccess = true; - } catch (Exception ex) { - log.debug("sessionId", "idType", "id", ExceptionUtils.getStackTrace(ex)); - log.error("sessionId", "idType", "id", - "In bookAppointment method of Booking Service- " + ex.getMessage()); - new BookingExceptionCatcher().handle(ex, responseDTO); - } finally { - if (isSaveSuccess) { - setAuditValues(EventId.PRE_407.toString(), EventName.PERSIST.toString(), - EventType.BUSINESS.toString(), "Appointment booked successfully", - AuditLogVariables.MULTIPLE_ID.toString(), authUserDetails().getUserId(), - authUserDetails().getUsername(), bookingRequestDTOs.getRequest().getRegistrationCenterId()); - } else { - setAuditValues(EventId.PRE_405.toString(), EventName.EXCEPTION.toString(), - EventType.SYSTEM.toString(), "Appointment failed to book", - AuditLogVariables.NO_ID.toString(), authUserDetails().getUserId(), - authUserDetails().getUsername(), bookingRequestDTOs.getRequest().getRegistrationCenterId()); - } - } - responseDTO.setResponsetime(serviceUtil.getCurrentResponseTime()); - responseDTO.setResponse(response); - log.info("Sync block :", preRegistrationId, " End", ""); - return responseDTO; - } - } - - /* - * (non-Javadoc) - * - * @see io.mosip.preregistration.booking.serviceimpl.service.BookingServiceIntf# - * bookMultiAppointment(io.mosip.preregistration.core.common.dto.MainRequestDTO) - */ - @Override - @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class) - public MainResponseDTO bookMultiAppointment(MainRequestDTO bookingRequestDTOs) { - - log.info("sessionId", "idType", "id", "In bookMultiAppointment method of Booking Service"); - - bookingLock.setDate(bookingRequestDTOs.getRequest().getBookingRequest().get(0).getRegDate()); - bookingLock.setRegistrationCenter(bookingRequestDTOs.getRequest().getBookingRequest().get(0).getRegDate()); - bookingLock.setTimeslot(bookingRequestDTOs.getRequest().getBookingRequest().get(0).getSlotFromTime()); - - synchronized (bookingLock) { - log.info("Sync block :", bookingRequestDTOs.getRequest().getBookingRequest().get(0).getPreRegistrationId(), - " Start", ""); - MainResponseDTO responseDTO = new MainResponseDTO<>(); - BookingStatus response = new BookingStatus(); - responseDTO.setId(idUrlBookAppointment); - responseDTO.setVersion(versionUrl); - boolean isSaveSuccess = false; - List respList = new ArrayList<>(); - try { - for (MultiBookingRequestDTO bookingRequestDTO : bookingRequestDTOs.getRequest().getBookingRequest()) { - Map dateMap = new HashMap<>(); - dateMap.put(RequestCodes.REG_DATE.getCode(), bookingRequestDTO.getRegDate()); - dateMap.put(RequestCodes.FROM_SLOT_TIME.getCode(), bookingRequestDTO.getSlotFromTime()); - dateMap.put(RequestCodes.PRE_REGISTRAION_ID.getCode(), bookingRequestDTO.getPreRegistrationId()); - if (serviceUtil.validateAppointmentDate(dateMap)) { - /* Getting Status From Demographic */ - String preRegStatusCode = serviceUtil - .getApplicationBookingStatus(bookingRequestDTO.getPreRegistrationId()); - log.debug("preRegStatusCode" + preRegStatusCode); - - if (preRegStatusCode.equals(StatusCodes.APPLICATION_INCOMPLETE.getCode()) - || preRegStatusCode.equals(StatusCodes.PREFETCHED.getCode())) { - - if (preRegStatusCode.equals(StatusCodes.APPLICATION_INCOMPLETE.getCode())) { - throw new DemographicGetStatusException(ErrorCodes.PRG_BOOK_RCI_036.getCode(), - ErrorMessages.APPOINTMENT_CANNOT_BE_BOOKED_FOR_INCOMPLETE_APPLICATION - .getMessage()); - } else { - throw new DemographicGetStatusException(ErrorCodes.PRG_BOOK_RCI_036.getCode(), - ErrorMessages.APPOINTMENT_CANNOT_BE_BOOKED_FOR_PREFETCHED_APPLICATION - .getMessage()); - } - - } - - // Taking one booking request from multiple - BookingRequestDTO bookingRequest = new BookingRequestDTO(); - bookingRequest.setRegDate(bookingRequestDTO.getRegDate()); - bookingRequest.setRegistrationCenterId(bookingRequestDTO.getRegistrationCenterId()); - bookingRequest.setSlotFromTime(bookingRequestDTO.getSlotFromTime()); - bookingRequest.setSlotToTime(bookingRequestDTO.getSlotToTime()); - - if (serviceUtil.mandatoryParameterCheck(bookingRequestDTO.getPreRegistrationId(), - bookingRequest) - && serviceUtil.slotTimeValidCheck(bookingRequestDTO.getPreRegistrationId(), - bookingRequest)) { - - /* Checking the availability of slots */ - checkSlotAvailability(bookingRequest); - - if (preRegStatusCode.equals(StatusCodes.PENDING_APPOINTMENT.getCode()) - || preRegStatusCode.equals(StatusCodes.CANCELLED.getCode())) { - - /* Creating new booking */ - respList.add(book(bookingRequestDTO.getPreRegistrationId(), bookingRequest)); - - } else if (preRegStatusCode.equals(StatusCodes.BOOKED.getCode())) { - - /* Concatenating Booking date and slot from time */ - RegistrationBookingEntity bookingEntity = bookingDAO - .findByPreRegistrationId(bookingRequestDTO.getPreRegistrationId()); - BookingRequestDTO oldBooking = new BookingRequestDTO(); - oldBooking.setRegDate(bookingEntity.getRegDate().toString()); - oldBooking.setRegistrationCenterId(bookingEntity.getRegistrationCenterId()); - oldBooking.setSlotFromTime(bookingEntity.getSlotFromTime().toString()); - oldBooking.setSlotToTime(bookingEntity.getSlotToTime().toString()); - - String str = bookingEntity.getRegDate() + " " + bookingEntity.getSlotFromTime(); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); - LocalDateTime bookedDateTime = LocalDateTime.parse(str, formatter); - - log.info("sessionId", "idType", "id", - "In bookMultiAppointment method of Booking Service for booking Date Time- " - + bookedDateTime); - /* Time span check for re-book */ - serviceUtil.timeSpanCheckForRebook(bookedDateTime, bookingRequestDTOs.getRequesttime()); - - /* Deleting old booking */ - deleteOldBooking(bookingRequestDTO.getPreRegistrationId()); - - /* Increase availability */ - increaseAvailability(oldBooking); - - /* Creating new booking */ - respList.add(book(bookingRequestDTO.getPreRegistrationId(), bookingRequest)); - - } else if (preRegStatusCode.equals(StatusCodes.EXPIRED.getCode())) { - - /* Deleting old booking */ - deleteOldBooking(bookingRequestDTO.getPreRegistrationId()); - - /* Creating new booking */ - respList.add(book(bookingRequestDTO.getPreRegistrationId(), bookingRequest)); - } - - } - } - } - isSaveSuccess = true; - } catch (Exception ex) { - log.debug("sessionId", "idType", "id", ExceptionUtils.getStackTrace(ex)); - log.error("sessionId", "idType", "id", - "In bookMultiAppointment method of Booking Service- " + ex.getMessage()); - new BookingExceptionCatcher().handle(ex, responseDTO); - } finally { - if (isSaveSuccess) { - setAuditValues(EventId.PRE_407.toString(), EventName.PERSIST.toString(), - EventType.BUSINESS.toString(), "Appointment booked successfully", - AuditLogVariables.MULTIPLE_ID.toString(), authUserDetails().getUserId(), - authUserDetails().getUsername(), - bookingRequestDTOs.getRequest().getBookingRequest().get(0).getRegistrationCenterId()); - } else { - setAuditValues(EventId.PRE_405.toString(), EventName.EXCEPTION.toString(), - EventType.SYSTEM.toString(), "Appointment failed to book", - AuditLogVariables.NO_ID.toString(), authUserDetails().getUserId(), - authUserDetails().getUsername(), - bookingRequestDTOs.getRequest().getBookingRequest().get(0).getRegistrationCenterId()); - } - } - responseDTO.setResponsetime(serviceUtil.getCurrentResponseTime()); - response.setBookingStatusResponse(respList); - responseDTO.setResponse(response); - log.info("Sync block :", bookingRequestDTOs.getRequest().getBookingRequest().get(0).getPreRegistrationId(), - " End", ""); - return responseDTO; - } - } - - /* - * (non-Javadoc) - * - * @see io.mosip.preregistration.booking.serviceimpl.service.BookingServiceIntf# - * getAppointmentDetails(java.lang.String) - */ - @Override - public MainResponseDTO getAppointmentDetails(String preRegID) { - log.info("sessionId", "idType", "id", "In getAppointmentDetails method of Booking Service"); - BookingRegistrationDTO bookingRegistrationDTO = new BookingRegistrationDTO(); - MainResponseDTO responseDto = new MainResponseDTO<>(); - responseDto.setId(idUrlFetch); - responseDto.setVersion(versionUrl); - RegistrationBookingEntity entity = null; - try { - this.applicationIdValidation(preRegID); - // This call will check if the PRID belongs to the logged in user or not - serviceUtil.checkApplicationStatus(preRegID); - entity = bookingDAO.findByPreRegistrationId(preRegID); - - bookingRegistrationDTO.setRegDate(entity.getRegDate().toString()); - bookingRegistrationDTO.setRegistrationCenterId(entity.getRegistrationCenterId()); - bookingRegistrationDTO.setSlotFromTime(entity.getSlotFromTime().toString()); - bookingRegistrationDTO.setSlotToTime(entity.getSlotToTime().toString()); - responseDto.setResponse(bookingRegistrationDTO); - - responseDto.setErrors(null); - responseDto.setResponsetime(serviceUtil.getCurrentResponseTime()); - - } catch (Exception ex) { - log.debug("sessionId", "idType", "id", ExceptionUtils.getStackTrace(ex)); - log.error("sessionId", "idType", "id", - "In getAppointmentDetails method of Booking Service- " + ex.getMessage()); - new BookingExceptionCatcher().handle(ex, responseDto); - } - - return responseDto; - } - - private void applicationIdValidation(String applicationId) { - if (applicationId == null || applicationId.trim().isEmpty()) { - throw new InvalidIDException( - ErrorCodes.PRG_BOOK_RCI_022.getCode(), - "preRegistrationId cannot be empty." - ); - } - } - - /* - * (non-Javadoc) - * - * @see io.mosip.preregistration.booking.serviceimpl.service.BookingServiceIntf# - * cancelAppointment(java.lang.String) - */ - @Override - @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class) - public MainResponseDTO cancelAppointment(String preRegistrationId) { - log.info("sessionId", "idType", "id", "In cancelAppointment method of Booking Service"); - MainResponseDTO responseDto = new MainResponseDTO<>(); - boolean isBatchUser = false; - responseDto.setId(idUrlCancel); - responseDto.setVersion(versionUrl); - responseDto.setResponse(cancelBooking(preRegistrationId, isBatchUser)); - - responseDto.setResponsetime(serviceUtil.getCurrentResponseTime()); - - return responseDto; - } - - /* - * (non-Javadoc) - * - * @see io.mosip.preregistration.booking.serviceimpl.service.BookingServiceIntf# - * cancelAppointmentBatch(java.lang.String) - */ - @Override - @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class) - public MainResponseDTO cancelAppointmentBatch(String preRegistrationId) { - log.info("sessionId", "idType", "id", "In cancelAppointment method of Booking Service"); - MainResponseDTO responseDto = new MainResponseDTO<>(); - boolean isBatchUser = true; - responseDto.setId(idUrlCancel); - responseDto.setVersion(versionUrl); - responseDto.setResponse(cancelBooking(preRegistrationId, isBatchUser)); - - responseDto.setResponsetime(serviceUtil.getCurrentResponseTime()); - - return responseDto; - } - - /* - * (non-Javadoc) - * - * @see - * io.mosip.preregistration.booking.serviceimpl.service.BookingServiceIntf#book( - * java.lang.String, - * io.mosip.preregistration.booking.serviceimpl.dto.BookingRequestDTO) - */ - @Override - //Please note that this method is NOT creating a new transaction. - //@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class) - public BookingStatusDTO book(String preRegistrationId, BookingRequestDTO bookingRequestDTO) { - log.info("sessionId", "idType", "id", "In book method of Booking Service"); - BookingStatusDTO bookingStatusDTO = new BookingStatusDTO(); - MainResponseDTO response = new MainResponseDTO<>(); - response.setId(idUrlBookAppointment); - response.setVersion(versionUrl); - try { - AvailibityEntity availableEntity; - - availableEntity = bookingDAO.findFirstByRegDateAndRegcntrIdAndFromTimeAndToTime( - LocalDate.parse(bookingRequestDTO.getRegDate()), bookingRequestDTO.getRegistrationCenterId(), - LocalTime.parse(bookingRequestDTO.getSlotFromTime()), - LocalTime.parse(bookingRequestDTO.getSlotToTime())); - log.info("In Availablity of book method", - "available slots before update :" + availableEntity.getAvailableKiosks(), - " for Reg center" + availableEntity.getRegcntrId(), - " and Date and Time " + availableEntity.getRegDate() + " " + availableEntity.getFromTime()); - if (serviceUtil.isKiosksAvailable(availableEntity)) { - /* Updating booking */ - RegistrationBookingEntity bookingEntity = bookingDAO.saveRegistrationEntityForBooking( - serviceUtil.bookingEntitySetter(preRegistrationId, bookingRequestDTO)); - /* - * Best-effort backfill: a failure here must never fail the booking. The - * booking's own crBy is already canonical at this point, so ownership and - * auth are unaffected; missed rows self-heal on the user's next activity and - * are swept by the nightly identity reconciliation job. - */ - try { - applicationIdentityMigrationService.migrateRawUserToEffectiveUser(preRegistrationId, - bookingEntity.getCrBy()); - } catch (Exception migrationEx) { - log.error("sessionId", "idType", "id", - "Identity migration failed for preRegistrationId " + preRegistrationId - + ", booking continues - " + migrationEx.getMessage()); - log.debug("sessionId", "idType", "id", ExceptionUtils.getStackTrace(migrationEx)); - } - /* Reduce Availability */ - availableEntity.setAvailableKiosks(availableEntity.getAvailableKiosks() - 1); - AvailibityEntity availableUpdate = bookingDAO.updateAvailibityEntity(availableEntity); - - log.info("In Availablity of book method", - "available slots after upadate :" + availableUpdate.getAvailableKiosks(), - " for Reg center" + availableUpdate.getRegcntrId(), - " and Date and Time " + availableUpdate.getRegDate() + " " + availableUpdate.getFromTime()); - - /* Updating demographic */ - // serviceUtil.updateDemographicStatus(preRegistrationId, - // StatusCodes.BOOKED.getCode()); - bookingStatusDTO.setBookingMessage("Appointment booked successfully"); - - } - - } catch (Exception ex) { - log.debug("sessionId", "idType", "id", ExceptionUtils.getStackTrace(ex)); - log.error("sessionId", "idType", "id", "In book method of Booking Service- " + ex.getMessage()); - new BookingExceptionCatcher().handle(ex, response); - } - - return bookingStatusDTO; - } - - /* - * (non-Javadoc) - * - * @see io.mosip.preregistration.booking.serviceimpl.service.BookingServiceIntf# - * cancelBooking(java.lang.String, boolean) - */ - @Override - //Please note that this method is NOT creating a new transaction. - //@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class) - public CancelBookingResponseDTO cancelBooking(String preRegistrationId, boolean isBatchUser) { - log.info("sessionId", "idType", "id", "In cancelBooking method of Booking Service"); - CancelBookingResponseDTO cancelBookingResponseDTO = new CancelBookingResponseDTO(); - MainResponseDTO response = new MainResponseDTO<>(); - response.setId(idUrlCancel); - response.setVersion(versionUrl); - boolean isSaveSuccess = false; - AvailibityEntity availableEntity; - RegistrationBookingEntity bookingEntity; - try { - if (serviceUtil.mandatoryParameterCheckforCancel(preRegistrationId)) { - if (serviceUtil.getDemographicStatusForCancel(preRegistrationId)) { - /* Getting Booking details */ - bookingEntity = bookingDAO.findByPreRegistrationId(preRegistrationId); - - availableEntity = bookingDAO.findFirstByRegDateAndRegcntrIdAndFromTimeAndToTime( - bookingEntity.getRegDate(), bookingEntity.getRegistrationCenterId(), - bookingEntity.getSlotFromTime(), bookingEntity.getSlotToTime()); - - /* For batch condition will skip */ - if (!isBatchUser) { - String str = bookingEntity.getRegDate() + " " + bookingEntity.getSlotFromTime(); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); - LocalDateTime bookedDateTime = LocalDateTime.parse(str, formatter); - - serviceUtil.timeSpanCheckForCancle(bookedDateTime); - } - /* - * Best-effort backfill. The resolved id is not used beyond this call, so - * an unresolvable legacy crBy must not block a cancellation. - */ - try { - String effectiveUserId = applicationIdentityMigrationService - .resolveEffectiveUserId(bookingEntity.getCrBy()); - applicationIdentityMigrationService.migrateRawUserToEffectiveUser(preRegistrationId, - effectiveUserId); - } catch (Exception migrationEx) { - log.error("sessionId", "idType", "id", - "Identity migration failed for preRegistrationId " + preRegistrationId - + ", cancellation continues - " + migrationEx.getMessage()); - log.debug("sessionId", "idType", "id", ExceptionUtils.getStackTrace(migrationEx)); - } - /* Deleting the canceled booking */ - // bookingDAO.deleteRegistrationEntity(bookingEntity); - bookingDAO.deleteByPreRegistrationId(preRegistrationId); - - /* Update the status to Canceled in demographic Table */ - // serviceUtil.updateDemographicStatus(preRegistrationId, - // StatusCodes.CANCELLED.getCode()); - - /* No. of Availability. update */ - availableEntity.setAvailableKiosks(availableEntity.getAvailableKiosks() + 1); - - bookingDAO.updateAvailibityEntity(availableEntity); - - cancelBookingResponseDTO.setTransactionId(UUIDGeneratorUtil.generateId()); - cancelBookingResponseDTO - .setMessage("Appointment for the selected application has been successfully cancelled"); - - } - } - isSaveSuccess = true; - } catch (Exception ex) { - log.debug("sessionId", "idType", "id", ExceptionUtils.getStackTrace(ex)); - log.error("sessionId", "idType", "id", "In cancelBooking method of Booking Service- " + ex.getMessage()); - new BookingExceptionCatcher().handle(ex, response); - } finally { - - if (isSaveSuccess) { - setAuditValues(EventId.PRE_402.toString(), EventName.UPDATE.toString(), EventType.BUSINESS.toString(), - "Booking cancel successfully", AuditLogVariables.MULTIPLE_ID.toString(), - authUserDetails().getUserId(), authUserDetails().getUsername(), null); - } else { - setAuditValues(EventId.PRE_405.toString(), EventName.EXCEPTION.toString(), EventType.SYSTEM.toString(), - "Booking failed to cancel", AuditLogVariables.NO_ID.toString(), authUserDetails().getUserId(), - authUserDetails().getUsername(), null); - } - } - return cancelBookingResponseDTO; - } - - /* - * (non-Javadoc) - * - * @see io.mosip.preregistration.booking.serviceimpl.service.BookingServiceIntf# - * deleteBooking(java.lang.String) - */ - @Override - @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class) - public MainResponseDTO deleteBooking(String preregId) { - log.info("sessionId", "idType", "id", "In deleteIndividual method of pre-registration service "); - MainResponseDTO response = new MainResponseDTO<>(); - response.setId(idUrlDelete); - response.setVersion(versionUrl); - DeleteBookingDTO deleteDto = new DeleteBookingDTO(); - Map requestParamMap = new HashMap<>(); - AvailibityEntity availableEntity; - boolean isSaveSuccess = false; - try { - requestParamMap.put(RequestCodes.PRE_REGISTRAION_ID.getCode(), preregId); - if (validationUtil.requstParamValidator(requestParamMap) - && serviceUtil.checkApplicationStatus(preregId)) { - RegistrationBookingEntity registrationEntityList = bookingDAO.findByPreRegistrationId(preregId); - /* - * Best-effort backfill: a failure here must never fail the deletion. The - * backfill resolves each column from its own stored value, so the booking's - * own crBy is all it needs. - */ - try { - applicationIdentityMigrationService.migrateRawUserToEffectiveUser(preregId, - registrationEntityList.getCrBy()); - } catch (Exception migrationEx) { - log.error("sessionId", "idType", "id", "Identity migration failed for preRegistrationId " - + preregId + ", deletion continues - " + migrationEx.getMessage()); - log.debug("sessionId", "idType", "id", ExceptionUtils.getStackTrace(migrationEx)); - } - String str = registrationEntityList.getRegDate() + " " + registrationEntityList.getSlotFromTime(); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); - LocalDateTime bookedDateTime = LocalDateTime.parse(str, formatter); - serviceUtil.timeSpanCheckForCancle(bookedDateTime); - bookingDAO.deleteByPreRegistrationId(preregId); - availableEntity = bookingDAO.findFirstByRegDateAndRegcntrIdAndFromTimeAndToTime( - LocalDate.parse(registrationEntityList.getRegDate().toString()), - registrationEntityList.getRegistrationCenterId(), - LocalTime.parse(registrationEntityList.getSlotFromTime().toString()), - LocalTime.parse(registrationEntityList.getSlotToTime().toString())); - /* No. of Availability. update */ - availableEntity.setAvailableKiosks(availableEntity.getAvailableKiosks() + 1); - - /* Updating slot in DB */ - bookingDAO.updateAvailibityEntity(availableEntity); - - deleteDto.setPreRegistrationId(registrationEntityList.getPreregistrationId()); - deleteDto.setDeletedDateTime(new Date(System.currentTimeMillis())); - /* - * Response-only attribution, resolved after the deletion so it can never - * block it. An unresolvable legacy identifier leaves the field unset - it - * must never fall back to the raw value, which would put the plaintext - * identifier back on the wire. The audit trail is unaffected: it records the - * authenticated caller, not this value. - */ - try { - deleteDto.setDeletedBy(applicationIdentityMigrationService - .resolveEffectiveUserId(registrationEntityList.getCrBy())); - } catch (Exception resolveEx) { - log.error("sessionId", "idType", "id", "Could not resolve deletedBy for preRegistrationId " - + preregId + ", field omitted - " + resolveEx.getMessage()); - log.debug("sessionId", "idType", "id", ExceptionUtils.getStackTrace(resolveEx)); - } - - } - isSaveSuccess = true; - } catch (Exception ex) { - log.debug("sessionId", "idType", "id", ExceptionUtils.getStackTrace(ex)); - log.error("sessionId", "idType", "id", "In deleteBooking method of Booking Service- " + ex.getMessage()); - new BookingExceptionCatcher().handle(ex, response); - } finally { - - if (isSaveSuccess) { - setAuditValues(EventId.PRE_403.toString(), EventName.DELETE.toString(), EventType.BUSINESS.toString(), - "Booking deleted successfully", AuditLogVariables.MULTIPLE_ID.toString(), - authUserDetails().getUserId(), authUserDetails().getUsername(), null); - } else { - setAuditValues(EventId.PRE_405.toString(), EventName.EXCEPTION.toString(), EventType.SYSTEM.toString(), - "Booking failed to delete", AuditLogVariables.NO_ID.toString(), authUserDetails().getUserId(), - authUserDetails().getUsername(), null); - } - } - - response.setResponsetime(serviceUtil.getCurrentResponseTime()); - response.setResponse(deleteDto); - return response; - } - - /* - * (non-Javadoc) - * - * @see io.mosip.preregistration.booking.serviceimpl.service.BookingServiceIntf# - * checkSlotAvailability(io.mosip.preregistration.booking.serviceimpl.dto. - * BookingRequestDTO) - */ - @Override - public void checkSlotAvailability(BookingRequestDTO bookingRequestDTO) { - MainResponseDTO response = new MainResponseDTO<>(); - response.setId(idUrlCheckSlotAvailability); - response.setVersion(versionUrl); - try { - List regCenter = serviceUtil.getRegCenterMasterData( - bookingRequestDTO.getRegistrationCenterId()); - Boolean isValidRegCenter = regCenter.stream() - .anyMatch(iterate -> iterate.getId().contains(bookingRequestDTO.getRegistrationCenterId())); - - if (!isValidRegCenter) { - throw new RecordNotFoundException(ErrorCodes.PRG_BOOK_RCI_035.getCode(), - ErrorMessages.REG_CENTER_ID_NOT_FOUND.getMessage()); - } - - bookingDAO.findRegistrationCenterId(bookingRequestDTO.getRegistrationCenterId()); - AvailibityEntity entity = bookingDAO.findByRegDateAndRegcntrIdAndFromTimeAndToTime( - LocalDate.parse(bookingRequestDTO.getRegDate()), bookingRequestDTO.getRegistrationCenterId(), - LocalTime.parse(bookingRequestDTO.getSlotFromTime()), - LocalTime.parse(bookingRequestDTO.getSlotToTime())); - log.info("In Availablity", "available slots :" + entity.getAvailableKiosks(), - " for Reg center" + entity.getRegcntrId(), - " and Date and Time " + entity.getRegDate() + " " + entity.getFromTime()); - - log.info("sessionId", "idType", "id", "In checkSlotAvailability method of Booking Service"); - if (entity.getAvailableKiosks() < 1) { - throw new AvailablityNotFoundException(ErrorCodes.PRG_BOOK_RCI_002.getCode(), - ErrorMessages.AVAILABILITY_NOT_FOUND_FOR_THE_SELECTED_TIME.getMessage()); - } - } catch (Exception ex) { - log.debug("sessionId", "idType", "id", ExceptionUtils.getStackTrace(ex)); - log.error("sessionId", "idType", "id", - "In checkSlotAvailability method of Booking Service for Exception- " + ex.getMessage()); - new BookingExceptionCatcher().handle(ex, response); - } - - } - - /* - * (non-Javadoc) - * - * @see io.mosip.preregistration.booking.serviceimpl.service.BookingServiceIntf# - * deleteOldBooking(java.lang.String) - */ - @Override - public boolean deleteOldBooking(String preId) { - MainResponseDTO response = new MainResponseDTO<>(); - response.setId(idUrlDeleteOld); - response.setVersion(versionUrl); - try { - int count = bookingDAO.deleteByPreRegistrationId(preId); - if (count > 0) { - log.info("sessionId", "idType", "id", "In deleteOldBooking method of Booking Service"); - return true; - } - } catch (Exception ex) { - log.debug("sessionId", "idType", "id", ExceptionUtils.getStackTrace(ex)); - log.error("sessionId", "idType", "id", - "In deleteOldBooking method of Booking Service for Exception- " + ex.getMessage()); - new BookingExceptionCatcher().handle(ex, response); - } - return false; - - } - - /* - * (non-Javadoc) - * - * @see io.mosip.preregistration.booking.serviceimpl.service.BookingServiceIntf# - * increaseAvailability(io.mosip.preregistration.booking.serviceimpl.dto. - * BookingRequestDTO) - */ - @Override - public boolean increaseAvailability(BookingRequestDTO oldBooking) { - MainResponseDTO response = new MainResponseDTO<>(); - response.setId(idUrlIncreaseAvailability); - response.setVersion(versionUrl); - try { - AvailibityEntity availableEntity; - availableEntity = bookingDAO.findByRegDateAndRegcntrIdAndFromTimeAndToTime( - LocalDate.parse(oldBooking.getRegDate()), oldBooking.getRegistrationCenterId(), - LocalTime.parse(oldBooking.getSlotFromTime()), LocalTime.parse(oldBooking.getSlotToTime())); - availableEntity.setAvailableKiosks(availableEntity.getAvailableKiosks() + 1); - bookingDAO.updateAvailibityEntity(availableEntity); - log.info("sessionId", "idType", "id", "In increaseAvailability method of Booking Service"); - - } catch (Exception ex) { - log.debug("sessionId", "idType", "id", ExceptionUtils.getStackTrace(ex)); - log.error("sessionId", "idType", "id", - "In increaseAvailability method of Booking Service for Exception- " + ex.getMessage()); - new BookingExceptionCatcher().handle(ex, response); - } - return true; - - } - - /* - * (non-Javadoc) - * - * @see io.mosip.preregistration.booking.serviceimpl.service.BookingServiceIntf# - * setAuditValues(java.lang.String, java.lang.String, java.lang.String, - * java.lang.String, java.lang.String, java.lang.String, java.lang.String, - * java.lang.String) - */ - @Override - public void setAuditValues(String eventId, String eventName, String eventType, String description, String idType, - String userId, String userName, String ref_id) { - AuditRequestDto auditRequestDto = new AuditRequestDto(); - auditRequestDto.setEventId(eventId); - auditRequestDto.setEventName(eventName); - auditRequestDto.setEventType(eventType); - auditRequestDto.setDescription(description); - auditRequestDto.setId(idType); - auditRequestDto.setSessionUserId(userId); - auditRequestDto.setSessionUserName(userName); - auditRequestDto.setModuleId(AuditLogVariables.BOOK.toString()); - auditRequestDto.setModuleName(AuditLogVariables.BOOKING_SERVICE.toString()); - auditRequestDto.setId(ref_id); - auditLogUtil.saveAuditDetails(auditRequestDto); - } - - /* - * (non-Javadoc) - * - * @see io.mosip.preregistration.booking.serviceimpl.service.BookingServiceIntf# - * getBookedPreRegistrationByDate(java.lang.String, java.lang.String, - * java.lang.String) - */ - - @Override - public MainResponseDTO getBookedPreRegistrationByDate(String fromDateStr, - String toDateStr, String regCenterId) { - log.info("sessionId", "idType", "id", "In getBookedPreRegistrationByDate method of booking service "); - MainResponseDTO response = new MainResponseDTO<>(); - response.setId(idUrlBookingByDate); - response.setVersion(versionUrl); - try { - - if (toDateStr == null || toDateStr.isEmpty()) { - toDateStr = fromDateStr; - } - String format = "yyyy-MM-dd"; - if (serviceUtil.validateFromDateAndToDate(fromDateStr, toDateStr, format)) { - DateTimeFormatter parseFormatter = DateTimeFormatter.ofPattern(format); - LocalDate fromDate = LocalDate.parse(fromDateStr, parseFormatter); - LocalDate toDate = LocalDate.parse(toDateStr, parseFormatter); - Map> idsWithSlotTime = new HashMap>(); - List details = bookingDAO.findByBookingDateBetweenAndRegCenterId(fromDate, toDate, regCenterId, - idsWithSlotTime); - PreRegIdsByRegCenterIdResponseDTO responseDTO = new PreRegIdsByRegCenterIdResponseDTO(); - responseDTO.setPreRegistrationIds(details); - responseDTO.setRegistrationCenterId(regCenterId); - - response.setResponse(responseDTO); - } - } catch (Exception ex) { - log.debug("sessionId", "idType", "id", ExceptionUtils.getStackTrace(ex)); - log.error("sessionId", "idType", "id", - "In getPreRegistrationByDate method of pre-registration service - " + ex.getMessage()); - new BookingExceptionCatcher().handle(ex, response); - } - response.setResponsetime(serviceUtil.getCurrentResponseTime()); - response.setId(idUrlBookingByDate); - response.setVersion(versionUrl); - response.setErrors(null); - return response; - } - - @Override - public MainResponseDTO getBookedPreRegistrations(String fromDateStr, String toDateStr, - String regCenterId) { - log.info("sessionId", "idType", "id", "In getBookedPreRegistrations method of booking service "); - MainResponseDTO response = new MainResponseDTO<>(); - response.setId(idUrlBookingByDate); - response.setVersion(versionUrl); - try { - - if (toDateStr == null || toDateStr.isEmpty()) { - toDateStr = fromDateStr; - } - String format = "yyyy-MM-dd"; - if (serviceUtil.validateFromDateAndToDate(fromDateStr, toDateStr, format)) { - DateTimeFormatter parseFormatter = DateTimeFormatter.ofPattern(format); - LocalDate fromDate = LocalDate.parse(fromDateStr, parseFormatter); - LocalDate toDate = LocalDate.parse(toDateStr, parseFormatter); - Map> idsWithSlotTime = new HashMap>(); - bookingDAO.findByBookingDateBetweenAndRegCenterId(fromDate, toDate, regCenterId, idsWithSlotTime); - BookingDataByRegIdDto responseDTO = new BookingDataByRegIdDto(); - responseDTO.setRegistrationCenterId(regCenterId); - responseDTO.setIdsWithAppointmentDate(idsWithSlotTime); - response.setResponse(responseDTO); - } - } catch (Exception ex) { - log.debug("sessionId", "idType", "id", ExceptionUtils.getStackTrace(ex)); - log.error("sessionId", "idType", "id", - "In getBookedPreRegistrations method of pre-registration service - " + ex.getMessage()); - new BookingExceptionCatcher().handle(ex, response); - } - response.setResponsetime(serviceUtil.getCurrentResponseTime()); - response.setId(idUrlBookingByDate); - response.setVersion(versionUrl); - response.setErrors(null); - return response; - - } -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/service/BookingServiceIntf.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/service/BookingServiceIntf.java deleted file mode 100644 index 39fadb70e41..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/service/BookingServiceIntf.java +++ /dev/null @@ -1,173 +0,0 @@ -package io.mosip.preregistration.booking.service; - - -import org.springframework.stereotype.Service; - -import io.mosip.preregistration.booking.dto.AvailabilityDto; -import io.mosip.preregistration.booking.dto.BookingDataByRegIdDto; -import io.mosip.preregistration.booking.dto.BookingRequestDTO; -import io.mosip.preregistration.booking.dto.BookingStatus; -import io.mosip.preregistration.booking.dto.BookingStatusDTO; -import io.mosip.preregistration.booking.dto.MultiBookingRequest; -import io.mosip.preregistration.core.common.dto.BookingRegistrationDTO; -import io.mosip.preregistration.core.common.dto.CancelBookingResponseDTO; -import io.mosip.preregistration.core.common.dto.DeleteBookingDTO; -import io.mosip.preregistration.core.common.dto.MainRequestDTO; -import io.mosip.preregistration.core.common.dto.MainResponseDTO; -import io.mosip.preregistration.core.common.dto.PreRegIdsByRegCenterIdResponseDTO; - -/** - * Booking operations: availability, book, multi-book, cancel, delete, and queries by centre/date. - */ -@Service -public interface BookingServiceIntf { - - /** - * Gives the availability details based on registrationId - * - * @param regID pass the RegistartionId - * @return AvailabilityDto return the registration details - */ - MainResponseDTO getAvailability(String regID); - - - /** - * This method use to book the appointment. - * - * @param bookingRequestDTO pass the booking details - * @return BookingStatusDTO response with booking status code - */ - MainResponseDTO bookAppointment(MainRequestDTO bookingRequestDTOs, - String preRegistrationId); - - /** - * This method will book the multiple appointments. - * - * @param bookingRequestDTOs pass the list of booking details - * @return BookingStatus response with list of booking status code - */ - MainResponseDTO bookMultiAppointment(MainRequestDTO bookingRequestDTOs); - - /** - * This method is for getting appointment details for given preRegistrationId. - * - * @param preRegID pass the preRegId - * @return BookingRegistrationDTO return the appointment details for given preRegId - */ - MainResponseDTO getAppointmentDetails(String preRegID); - - /** - * This method will cancel the appointment based on the preRegistrationId. - * - * @param preRegistrationId pass the preRegistrationId - * @return CancelBookingResponseDTO return the status code for cancel booking - */ - MainResponseDTO cancelAppointment(String preRegistrationId); - - /** - * This method will cancel the appointment using batch. - * - * @param preRegistrationId pass the preRegistartionId - * @return CancelBookingResponseDTO return the status code for cancel booking - */ - MainResponseDTO cancelAppointmentBatch(String preRegistrationId); - - /** - * - * This booking API will be called by bookAppointment method. - * - * @param preRegistrationId pass the peRegistartionId - * @param bookingRequestDTO pass the booking details - * @return BookingStatusDTO return the status code - */ - BookingStatusDTO book(String preRegistrationId, BookingRequestDTO bookingRequestDTO); - - /** - * This cancel API will be called by cancelAppointment method. - * - * @param preRegistrationId pass the preRegistrationId - * @param isBatchUser - * @return CancelBookingResponseDTO response with status code - */ - CancelBookingResponseDTO cancelBooking(String preRegistrationId, boolean isBatchUser); - - /** - * This Method is used to delete the Individual Application and documents - * associated with it - * - * @param preregId - * pass the preregId of individual - * @return response - * - */ - MainResponseDTO deleteBooking(String preregId); - - /** - * This Method is used to check the slot availability - * - * @param bookingRequestDTO - * pass the booking details - * - */ - void checkSlotAvailability(BookingRequestDTO bookingRequestDTO); - - /** - * This Method is used to delete the old booking - * - * @param preId - * pass the PreRegistrationId - * - */ - boolean deleteOldBooking(String preId); - - /** - * This Method is used to update the availability after cancel of booking - * - * @param oldBooking - * pass the old Booking details - * - */ - boolean increaseAvailability(BookingRequestDTO oldBooking); - - /** - * This method is used to audit all the booking events - * - * @param eventId - * @param eventName - * @param eventType - * @param description - * @param idType - */ - void setAuditValues(String eventId, String eventName, String eventType, String description, String idType, - String userId, String userName, String ref_id); - - /** - * This Method is used to retrieve booked PreIds by date and regCenterId** - * - * @param fromDate - * pass fromDate* - * @param toDate - * pass toDate* - * @param regCenterId - * @return MainResponseDTO - ***/ - - MainResponseDTO getBookedPreRegistrationByDate(String fromDateStr, - String toDateStr, String regCenterId); - - /** - * This Method is used to retrieve booked PreIds by date and regCenterId** - * - * @param fromDate - * pass fromDate* - * @param toDate - * pass toDate* - * @param regCenterId - * @return MainResponseDTO - ***/ - - MainResponseDTO getBookedPreRegistrations(String fromDateStr, - String toDateStr, String regCenterId); - - -} \ No newline at end of file diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/service/util/BookingLock.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/service/util/BookingLock.java deleted file mode 100644 index 8155aa09c29..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/service/util/BookingLock.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright - * - */ -package io.mosip.preregistration.booking.service.util; - -import org.springframework.stereotype.Component; - -import lombok.AllArgsConstructor; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; - -/** - * This class provides the locking object. - * - * @author Rudra Tripathy - * @since 1.0.0 - * - */ -@Component -@Getter -@Setter -@NoArgsConstructor -@AllArgsConstructor -public class BookingLock { - - String registrationCenter; - String date; - String timeslot; - - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - return 1; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) { - return false; - } - - BookingLock other = (BookingLock) obj; - if (date == null) { - if (other.date != null) - return false; - } else if (!date.equals(other.date)) { - return false; - } - if (registrationCenter == null) { - if (other.registrationCenter != null) - return false; - } else if (!registrationCenter.equals(other.registrationCenter)) { - return false; - } - if (timeslot == null) { - if (other.timeslot != null) - return false; - } else if (!timeslot.equals(other.timeslot)) { - return false; - } - - return true; - } - -} diff --git a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/service/util/BookingServiceUtil.java b/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/service/util/BookingServiceUtil.java deleted file mode 100644 index d8d690543bc..00000000000 --- a/pre-registration-booking-service/src/main/java/io/mosip/preregistration/booking/service/util/BookingServiceUtil.java +++ /dev/null @@ -1,775 +0,0 @@ -/* - * Copyright - * - */ -package io.mosip.preregistration.booking.service.util; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.LocalTime; -import java.time.ZoneId; -import java.time.ZonedDateTime; -import java.time.format.DateTimeParseException; -import java.time.temporal.ChronoUnit; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.TimeZone; - -import jakarta.annotation.PostConstruct; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.json.JsonMapper; -import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; -import com.fasterxml.jackson.module.afterburner.AfterburnerModule; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.ParameterizedTypeReference; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.stereotype.Component; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; -import org.springframework.web.client.HttpClientErrorException; -import org.springframework.web.client.RestClientException; -import org.springframework.web.client.RestTemplate; -import org.springframework.web.util.UriComponentsBuilder; - -import io.mosip.kernel.core.authmanager.authadapter.model.AuthUserDetails; -import io.mosip.kernel.core.exception.ExceptionUtils; -import io.mosip.kernel.core.exception.ServiceError; -import io.mosip.kernel.core.logger.spi.Logger; -import io.mosip.kernel.core.util.DateUtils2; -import io.mosip.preregistration.booking.codes.RequestCodes; -import io.mosip.preregistration.booking.dto.BookingRequestDTO; -import io.mosip.preregistration.booking.dto.CancelBookingDTO; -import io.mosip.preregistration.booking.dto.DateTimeDto; -import io.mosip.preregistration.booking.dto.RegistrationCenterDto; -import io.mosip.preregistration.booking.dto.RegistrationCenterResponseDto; -import io.mosip.preregistration.booking.dto.SlotDto; -import io.mosip.preregistration.booking.entity.AvailibityEntity; -import io.mosip.preregistration.booking.errorcodes.ErrorCodes; -import io.mosip.preregistration.booking.errorcodes.ErrorMessages; -import io.mosip.preregistration.booking.exception.AppointmentCannotBeCanceledException; -import io.mosip.preregistration.booking.exception.AppointmentReBookingFailedException; -import io.mosip.preregistration.booking.exception.AvailablityNotFoundException; -import io.mosip.preregistration.booking.exception.BookingDataNotFoundException; -import io.mosip.preregistration.booking.exception.BookingDateNotSeletectedException; -import io.mosip.preregistration.booking.exception.BookingPreIdNotFoundException; -import io.mosip.preregistration.booking.exception.BookingRegistrationCenterIdNotFoundException; -import io.mosip.preregistration.booking.exception.BookingTimeSlotNotSeletectedException; -import io.mosip.preregistration.booking.exception.AppointmentBookingFailedException; -import io.mosip.preregistration.booking.exception.DemographicGetStatusException; -import io.mosip.preregistration.booking.exception.InvalidDateTimeFormatException; -import io.mosip.preregistration.booking.exception.RecordNotFoundException; -import io.mosip.preregistration.booking.exception.TimeSpanException; -import io.mosip.preregistration.core.code.StatusCodes; -import io.mosip.preregistration.core.common.dto.BookingRegistrationDTO; -import io.mosip.preregistration.core.common.dto.MainRequestDTO; -import io.mosip.preregistration.core.common.dto.MainResponseDTO; -import io.mosip.preregistration.core.common.dto.NotificationDTO; -import io.mosip.preregistration.core.common.dto.RequestWrapper; -import io.mosip.preregistration.core.common.dto.ResponseWrapper; -import io.mosip.preregistration.core.common.entity.RegistrationBookingEntity; -import io.mosip.preregistration.core.config.LoggerConfiguration; -import io.mosip.preregistration.core.exception.MasterDataNotAvailableException; -import io.mosip.preregistration.core.exception.NotificationException; -import io.mosip.preregistration.core.exception.RestCallException; -import io.mosip.preregistration.core.util.UUIDGeneratorUtil; -import io.mosip.preregistration.core.util.ValidationUtil; -import io.mosip.preregistration.core.common.service.UserDetailsService; -import io.mosip.preregistration.core.exception.UserLookupException; -import io.mosip.preregistration.core.util.GenericUtil; - -/** - * This class provides the utility methods for Booking application. - * - * @author Kishan Rathore - * @author Jagadishwari - * @author Ravi C. Balaji - * @since 1.0.0 - * - */ -@Component -public class BookingServiceUtil { - - @Qualifier("selfTokenRestTemplate") - @Autowired - private RestTemplate selfTokenRestTemplate; - - @Autowired - private RestTemplate restTemplate; - - @Autowired - private UserDetailsService userDetailsService; - - /** - * Reference for ${regCenter.url} from property file - */ - @Value("${regCenter.url}") - String regCenterUrl; - - /** - * Reference for ${holiday.url} from property file - */ - @Value("${holiday.url}") - String holidayListUrl; - - /** - * Reference for ${demographic.resource.url} from property file - */ - @Value("${demographic.resource.url}") - private String preRegResourceUrl; - - @Value("${preregistration.timespan.cancel}") - private long timeSpanCheckForCancel; - - @Value("${preregistration.timespan.rebook}") - private long timeSpanCheckForRebook; - - @Value("${mosip.utc-datetime-pattern}") - private String utcDateTimePattern; - - @Value("${notification.url}") - private String notificationResourseurl; - - @Value("${mosip.notification.timezone}") - private String specificZoneId; - - /** - * ObjectMapper global object creation - */ - private ObjectMapper mapper; - - @PostConstruct - public void init() { - mapper = JsonMapper.builder().addModule(new AfterburnerModule()).build(); - mapper.registerModule(new JavaTimeModule()); - } - - private Logger log = LoggerConfiguration.logConfig(BookingServiceUtil.class); - - public AuthUserDetails authUserDetails() { - return (AuthUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); - } - - /** - * This method will call kernel service for registration center date. - * - * @return List of RegistrationCenterDto - */ - public List getRegCenterMasterData(String regCenterId) { - log.info("sessionId", "idType", "id", "In callRegCenterDateRestService method of Booking Service Util"); - List regCenter = null; - try { - String regCentersDetailsPageNo = new StringBuilder(regCenterUrl).append("/").append(regCenterId) - .append("/all").toString(); - - UriComponentsBuilder regbuilder = UriComponentsBuilder.fromUriString(regCentersDetailsPageNo); - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_JSON); - HttpEntity> entity = new HttpEntity<>(headers); - String uriBuilder = regbuilder.build().encode().toUriString(); - log.info("sessionId", "idType", "id", - "In callRegCenterDateRestService method of Booking Service URL- " + uriBuilder); - ResponseEntity> responseEntity = selfTokenRestTemplate.exchange( - uriBuilder, HttpMethod.GET, entity, - new ParameterizedTypeReference>() { - }); - ResponseWrapper body = responseEntity.getBody(); - if (body != null) { - if (body.getErrors() != null && !body.getErrors().isEmpty()) { - throw new MasterDataNotAvailableException(body.getErrors().get(0).getErrorCode(), - body.getErrors().get(0).getMessage()); - } - regCenter = body.getResponse().getRegistrationCenters(); - } - if (regCenter == null || regCenter.isEmpty()) { - throw new MasterDataNotAvailableException(ErrorCodes.PRG_BOOK_RCI_020.getCode(), - ErrorMessages.MASTER_DATA_NOT_FOUND.getMessage()); - } - } catch (HttpClientErrorException ex) { - log.debug("sessionId", "idType", "id", ExceptionUtils.getStackTrace(ex)); - log.error("sessionId", "idType", "id", - "In callRegCenterDateRestService method of Booking Service Util for HttpClientErrorException- " - + ex.getMessage()); - throw new RestCallException(ErrorCodes.PRG_BOOK_RCI_020.getCode(), - ErrorMessages.MASTER_DATA_NOT_FOUND.getMessage()); - } - return regCenter; - } - - /** - * This method will call demographic service for status. - * - * @param preId - * @return status code - */ - public String getApplicationBookingStatus(String preId) { - log.info("sessionId", "idType", "id", "In callGetStatusRestService method of Booking Service Util"); - - MainResponseDTO getApplicationStatus = getApplicationStatus(preId); - - if (getApplicationStatus.getErrors() != null) { - throw new DemographicGetStatusException(getApplicationStatus.getErrors().get(0).getErrorCode(), - getApplicationStatus.getErrors().get(0).getMessage()); - } - return getApplicationStatus.getResponse(); - - } - - /** - * This method will call demographic service for cancel status. - * - * @param preId - * @return status code - */ - public boolean getDemographicStatusForCancel(String preId) { - log.info("sessionId", "idType", "id", "In callGetStatusForCancelRestService method of Booking Service Util"); - - MainResponseDTO getApplicationStatus = getApplicationStatus(preId); - if (getApplicationStatus.getErrors() != null) { - throw new DemographicGetStatusException(getApplicationStatus.getErrors().get(0).getErrorCode(), - getApplicationStatus.getErrors().get(0).getMessage()); - } - String statusCode = getApplicationStatus.getResponse(); - - if (!statusCode.equals(StatusCodes.BOOKED.getCode())) { - if (statusCode.equals(StatusCodes.PENDING_APPOINTMENT.getCode()) - || statusCode.equals(StatusCodes.APPLICATION_INCOMPLETE.getCode())) { - throw new BookingDataNotFoundException(ErrorCodes.PRG_BOOK_RCI_013.getCode(), - ErrorMessages.BOOKING_DATA_NOT_FOUND.getMessage()); - } - - else { - throw new AppointmentCannotBeCanceledException(ErrorCodes.PRG_BOOK_RCI_018.getCode(), - ErrorMessages.APPOINTMENT_CANNOT_BE_CANCELED.getMessage()); - } - - } - return true; - } - - /** - * This method will call demographic service to get application status for - * delete flow and it will also check if the PRID belongs to the logged in user - * or not. - * - * @param preId - * @return status code - */ - public boolean checkApplicationStatus(String preId) { - log.info("sessionId", "idType", "id", "In callgetDemographicStatusForDelete method of Booking Service Util"); - // This call will check if the PRID belongs to the logged in user or not - MainResponseDTO getApplicationStatus = getApplicationStatus(preId); - if (getApplicationStatus.getErrors() != null) { - throw new DemographicGetStatusException(getApplicationStatus.getErrors().get(0).getErrorCode(), - getApplicationStatus.getErrors().get(0).getMessage()); - } - return true; - } - - public boolean timeSpanCheckForCancle(LocalDateTime bookedDateTime) { - boolean isTimeSpanCheckForCancel = true; - ZonedDateTime currentTime = ZonedDateTime.now(); - LocalDateTime requestTimeCountrySpecific = currentTime.toInstant().atZone(ZoneId.of(specificZoneId)) - .toLocalDateTime(); - log.info("sessionId", "idType", "id", - "In timeSpanCheckForCancle method of Booking Service for request Date Time- " - + requestTimeCountrySpecific); - long hours = ChronoUnit.HOURS.between(requestTimeCountrySpecific, bookedDateTime); - if (timeSpanCheckForCancel > 0) { - if (hours >= timeSpanCheckForCancel) - isTimeSpanCheckForCancel = true; - else - throw new TimeSpanException(ErrorCodes.PRG_BOOK_RCI_026.getCode(), - ErrorMessages.CANCEL_BOOKING_CANNOT_BE_DONE.getMessage() + " " + timeSpanCheckForCancel - + "hours"); - } - return isTimeSpanCheckForCancel; - } - - public boolean timeSpanCheckForRebook(LocalDateTime bookedDateTime, Date requestTime) { - - boolean isTimeSpanCheckForRebook = true; - LocalDateTime requestTimeCountrySpecific = requestTime.toInstant().atZone(ZoneId.of(specificZoneId)) - .toLocalDateTime(); - - log.info("sessionId", "idType", "id", - "In timeSpanCheckForRebook method of Booking Service for request Date Time- " - + requestTimeCountrySpecific); - long hours = ChronoUnit.HOURS.between(requestTimeCountrySpecific, bookedDateTime); - - if (timeSpanCheckForRebook > 0) { - if (hours >= timeSpanCheckForRebook) - isTimeSpanCheckForRebook = true; - - else - throw new TimeSpanException(ErrorCodes.PRG_BOOK_RCI_026.getCode(), - ErrorMessages.BOOKING_CANNOT_BE_DONE.getMessage() + " " + timeSpanCheckForRebook + " hours"); - } - return isTimeSpanCheckForRebook; - - } - - /** - * This method will check mandatory parameter check. - * - * @param bookingDto - * @return true or false - * @throws java.text.ParseException - */ - public boolean mandatoryParameterCheck(String preRegistrationId, BookingRequestDTO bookingRequestDTO) { - log.info("sessionId", "idType", "id", "In mandatoryParameterCheck method of Booking Service Util"); - boolean flag = true; - if (isNull(preRegistrationId)) { - throw new BookingPreIdNotFoundException(ErrorCodes.PRG_BOOK_RCI_006.getCode(), - ErrorMessages.PREREGISTRATION_ID_NOT_ENTERED.getMessage()); - } else if (bookingRequestDTO != null) { - if (isNull(bookingRequestDTO.getRegistrationCenterId())) { - throw new BookingRegistrationCenterIdNotFoundException(ErrorCodes.PRG_BOOK_RCI_007.getCode(), - ErrorMessages.REGISTRATION_CENTER_ID_NOT_ENTERED.getMessage()); - } else if (isNull(bookingRequestDTO.getRegDate())) { - throw new BookingDateNotSeletectedException(ErrorCodes.PRG_BOOK_RCI_008.getCode(), - ErrorMessages.BOOKING_DATE_TIME_NOT_SELECTED.getMessage()); - } else if (isNull(bookingRequestDTO.getSlotFromTime()) || isNull(bookingRequestDTO.getSlotToTime())) { - throw new BookingTimeSlotNotSeletectedException(ErrorCodes.PRG_BOOK_RCI_003.getCode(), - ErrorMessages.USER_HAS_NOT_SELECTED_TIME_SLOT.getMessage()); - } - } else { - flag = false; - } - return flag; - - } - - /** - * This method will check if Slot Time is Valid or not. - * - * @param preRegistrationId - * @param bookingDto - * @return true or false - */ - public boolean slotTimeValidCheck(String preRegistrationId, BookingRequestDTO bookingRequestDTO) { - log.info("sessionId", "idType", "id", "In slotTimeValidCheck method of Booking Service Util"); - boolean flag = true; - try { - LocalTime.parse(bookingRequestDTO.getSlotFromTime()); - LocalTime.parse(bookingRequestDTO.getSlotToTime()); - } catch (DateTimeParseException e) { - throw new BookingTimeSlotNotSeletectedException(ErrorCodes.PRG_BOOK_RCI_003.getCode(), - ErrorMessages.USER_HAS_NOT_SELECTED_TIME_SLOT.getMessage()); - } - return flag; - } - - /** - * This method is used as Null checker for different input keys. - * - * @param key pass the key - * @return true if key not null and return false if key is null. - */ - - public boolean isNull(Object key) { - log.info("sessionId", "idType", "id", "In isNull method of Booking Service Util"); - if (key instanceof String) { - if (key.equals("") || ((String) key).trim().length() == 0) - return true; - } else { - if (key == null) - return true; - } - return false; - } - - /** - * - * @param date - * @param dateTimeList - * @param dateTime - * @param entity - * @return - */ - public int slotSetter(LocalDate date, List dateTimeList, DateTimeDto dateTime, - List entity) { - int noOfHoliday = 0; - List slotList = new ArrayList<>(); - for (AvailibityEntity en : entity) { - if (en.getAvailableKiosks() > 0) { - SlotDto slots = new SlotDto(); - slots.setAvailability(en.getAvailableKiosks()); - slots.setFromTime(en.getFromTime()); - slots.setToTime(en.getToTime()); - slotList.add(slots); - } - } - if (entity.size() == 1) { - dateTime.setHoliday(true); - noOfHoliday++; - } else { - dateTime.setHoliday(false); - } - if (!slotList.isEmpty()) { - dateTime.setTimeSlots(slotList); - dateTime.setDate(date.toString()); - dateTimeList.add(dateTime); - } - return noOfHoliday; - - } - - /** - * This method will do mandatory parameter check for cancel. - * - * @param cancelBookingDTO - * @return true or false - */ - public boolean mandatoryParameterCheckforCancel(String preRegistrationId) { - log.info("sessionId", "idType", "id", "In mandatoryParameterCheckforCancel method of Booking Service Util"); - boolean flag = true; - - if (isNull(preRegistrationId)) { - throw new BookingPreIdNotFoundException(ErrorCodes.PRG_BOOK_RCI_006.getCode(), - ErrorMessages.PREREGISTRATION_ID_NOT_ENTERED.getMessage()); - } - - return flag; - - } - - /** - * This method will check for duplicates. - * - * @param oldBookingRegistrationDTO - * @param newBookingRegistrationDTO - * @return boolean - */ - public boolean isNotDuplicate(BookingRegistrationDTO oldBookingRegistrationDTO, - BookingRegistrationDTO newBookingRegistrationDTO) { - log.info("sessionId", "idType", "id", "In isNotDuplicate method of Booking Service Util"); - if (oldBookingRegistrationDTO.getRegDate().equals(newBookingRegistrationDTO.getRegDate()) - && oldBookingRegistrationDTO.getRegistrationCenterId() - .equals(newBookingRegistrationDTO.getRegistrationCenterId()) - && oldBookingRegistrationDTO.getSlotFromTime().equals(newBookingRegistrationDTO.getSlotFromTime()) - && oldBookingRegistrationDTO.getSlotToTime().equals(newBookingRegistrationDTO.getSlotToTime())) { - throw new AppointmentReBookingFailedException(ErrorCodes.PRG_BOOK_RCI_021.getCode(), - ErrorMessages.APPOINTMENT_REBOOKING_FAILED.getMessage()); - } - return true; - } - - /** - * This method is used to add the initial request values into a map for request - * map. - * - * @param MainRequestDTO pass requestDTO - * @return a map for request request map - */ - public Map prepareRequestMap(MainRequestDTO requestDto) { - log.info("sessionId", "idType", "id", "In prepareRequestMap method of Booking Service Util"); - Map requestMap = new HashMap<>(); - requestMap.put("id", requestDto.getId()); - requestMap.put("ver", requestDto.getVersion()); - requestMap.put("reqTime", new SimpleDateFormat(utcDateTimePattern).format(requestDto.getRequesttime())); - requestMap.put("request", requestDto.getRequest().toString()); - return requestMap; - } - - /** - * Helper method for setting CancelBookingDTO. - * - * @param preRegistrationId - * @param oldBookingRegistrationDTO - * @return - */ - public CancelBookingDTO cancelBookingDtoSetter(String preRegistrationId, - BookingRegistrationDTO oldBookingRegistrationDTO) { - log.info("sessionId", "idType", "id", "In cancelBookingDtoSetter method of Booking Service Util"); - CancelBookingDTO cancelBookingDTO = new CancelBookingDTO(); - cancelBookingDTO.setRegistrationCenterId(oldBookingRegistrationDTO.getRegistrationCenterId()); - cancelBookingDTO.setRegDate(oldBookingRegistrationDTO.getRegDate()); - cancelBookingDTO.setSlotFromTime(oldBookingRegistrationDTO.getSlotFromTime()); - cancelBookingDTO.setSlotToTime(oldBookingRegistrationDTO.getSlotToTime()); - return cancelBookingDTO; - } - - public String getCurrentResponseTime() { - log.info("sessionId", "idType", "id", "In getCurrentResponseTime method of Booking Service Util"); - return DateUtils2.formatDate(new Date(System.currentTimeMillis()), utcDateTimePattern); - } - - /** - * This method will check for availability. - * - * @param availableEntity - * @return boolean - */ - public boolean isKiosksAvailable(AvailibityEntity availableEntity) { - log.info("sessionId", "idType", "id", "In isKiosksAvailable method of Booking Service Util"); - - if (availableEntity.getAvailableKiosks() > 0) { - return true; - } else { - throw new AvailablityNotFoundException(ErrorCodes.PRG_BOOK_RCI_002.getCode(), - ErrorMessages.AVAILABILITY_NOT_FOUND_FOR_THE_SELECTED_TIME.getMessage()); - } - } - - /** - * Helper method for setting RegistrationBookingEntity. - * - * @param preRegistrationId - * @param oldBookingRegistrationDTO - * @return - */ - public RegistrationBookingEntity bookingEntitySetter(String preRegistrationId, - BookingRequestDTO bookingRequestDTO) {// should set preid - log.info("sessionId", "idType", "id", "In bookingEntitySetter method of Booking Service Util"); - RegistrationBookingEntity entity = new RegistrationBookingEntity(); - //entity.setBookingPK(new RegistrationBookingPK(DateUtils2.parseDateToLocalDateTime(new Date()))); - entity.setBookingDateTime(DateUtils2.parseDateToLocalDateTime(new Date())); - entity.setRegistrationCenterId(bookingRequestDTO.getRegistrationCenterId()); - entity.setId(UUIDGeneratorUtil.generateId()); - entity.setLangCode("12L"); - String userId = authUserDetails().getUserId(); - entity.setCrBy(resolveEffectiveCrBy(userId)); - entity.setCrDate(DateUtils2.parseDateToLocalDateTime(new Date())); - entity.setRegDate(LocalDate.parse(bookingRequestDTO.getRegDate())); - entity.setSlotFromTime(LocalTime.parse(bookingRequestDTO.getSlotFromTime())); - entity.setSlotToTime(LocalTime.parse(bookingRequestDTO.getSlotToTime())); - entity.setPreregistrationId(preRegistrationId); - return entity; - } - - private String resolveEffectiveCrBy(String userId) { - String maskedUserId = GenericUtil.maskIdentifier(userId); - /* - * getOrCreateInternalUserId returns null for a null or blank id rather than - * throwing, so without this guard a missing authenticated user would flow - * through as a null crBy and fail only at the NOT NULL constraint - surfacing - * as an opaque "table not accessible" error instead of an identity one. - */ - if (userId == null || userId.isBlank()) { - log.warn("sessionId", "idType", "id", - "Cannot resolve effective booking user id: authenticated user id is absent"); - throw new AppointmentBookingFailedException(ErrorCodes.PRG_BOOK_RCI_005.getCode(), - ErrorMessages.APPOINTMENT_BOOKING_FAILED.getMessage()); - } - try { - String effectiveCrBy = userDetailsService.getOrCreateInternalUserId(userId); - boolean canonicalApplied = effectiveCrBy != null && !effectiveCrBy.isBlank() - && !effectiveCrBy.trim().equals(userId == null ? "" : userId.trim()); - log.info("sessionId", "idType", "id", - "Resolved effective user id for booking write. maskedUserId=" + maskedUserId - + ", canonicalApplied=" + canonicalApplied); - return effectiveCrBy; - } catch (UserLookupException ex) { - log.warn("sessionId", "idType", "id", - "Failed to resolve effective booking user id for " + maskedUserId); - throw new AppointmentBookingFailedException(ErrorCodes.PRG_BOOK_RCI_005.getCode(), - ErrorMessages.APPOINTMENT_BOOKING_FAILED.getMessage()); - } - } - - /** - * - * @param notificationDTO - * @param langCode - * @return NotificationResponseDTO - * @throws JsonProcessingException - */ - public void emailNotification(NotificationDTO notificationDTO, String langCode) throws JsonProcessingException { - String emailResourseUrl = notificationResourseurl + "/notify"; - ResponseEntity resp = null; - HttpHeaders headers = new HttpHeaders(); - MainRequestDTO request = new MainRequestDTO<>(); - mapper.setTimeZone(TimeZone.getDefault()); - try { - request.setRequest(notificationDTO); - request.setId("mosip.pre-registration.notification.notify"); - request.setVersion("1.0"); - request.setRequesttime(new Date()); - headers.setContentType(MediaType.MULTIPART_FORM_DATA); - MultiValueMap emailMap = new LinkedMultiValueMap<>(); - emailMap.add("NotificationRequestDTO", mapper.writeValueAsString(request)); - emailMap.add("langCode", langCode); - HttpEntity> httpEntity = new HttpEntity<>(emailMap, headers); - log.info("sessionId", "idType", "id", - "In emailNotification method of NotificationUtil service emailResourseUrl: " + emailResourseUrl); - resp = selfTokenRestTemplate.exchange(emailResourseUrl, HttpMethod.POST, httpEntity, String.class); - List validationErrorList = ExceptionUtils.getServiceErrorList(resp.getBody()); - if (validationErrorList != null && !validationErrorList.isEmpty()) { - throw new NotificationException(validationErrorList, null); - } - } catch (HttpClientErrorException ex) { - log.debug("sessionId", "idType", "id", ExceptionUtils.getStackTrace(ex)); - log.error("sessionId", "idType", "id", - "In emailNotification method of Booking Service Util for HttpClientErrorException- " - + ex.getMessage()); - throw new RestCallException(ErrorCodes.PRG_BOOK_RCI_033.getCode(), - ErrorMessages.NOTIFICATION_CALL_FAILED.getMessage()); - - } - } - - /** - * This method is used to check whether the appointment date is valid or not - * - * @param requestMap - * @return true if the appointment date time is not older date or false if the - * appointment date is older date - */ - public boolean validateAppointmentDate(Map requestMap) { - try { - if (requestMap.get(RequestCodes.REG_DATE.getCode()) != null - && !requestMap.get(RequestCodes.REG_DATE.getCode()).isEmpty()) { - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); - sdf.setLenient(false); - sdf.parse(requestMap.get(RequestCodes.REG_DATE.getCode())); - LocalDate localDate = LocalDate.parse(requestMap.get(RequestCodes.REG_DATE.getCode())); - Date currentDate = new Date(); - LocalDate date = currentDate.toInstant().atZone(ZoneId.of(specificZoneId)).toLocalDate(); - - if (localDate.isBefore(date)) { - throw new InvalidDateTimeFormatException( - ErrorCodes.PRG_BOOK_RCI_031.getCode(), ErrorMessages.INVALID_BOOKING_DATE_TIME.getMessage() - + " found for - " + requestMap.get(RequestCodes.PRE_REGISTRAION_ID.getCode()), - null); - } else if (localDate.isEqual(date) && (requestMap.get(RequestCodes.FROM_SLOT_TIME.getCode()) != null - && !requestMap.get(RequestCodes.FROM_SLOT_TIME.getCode()).isEmpty())) { - LocalTime localTime = LocalTime.parse(requestMap.get(RequestCodes.FROM_SLOT_TIME.getCode())); - LocalTime time = currentDate.toInstant().atZone(ZoneId.of(specificZoneId)).toLocalTime(); - if (localTime.isBefore(time)) { - throw new InvalidDateTimeFormatException(ErrorCodes.PRG_BOOK_RCI_031.getCode(), - ErrorMessages.INVALID_BOOKING_DATE_TIME.getMessage() + " found for - " - + requestMap.get(RequestCodes.PRE_REGISTRAION_ID.getCode()), - null); - } - } - } - } catch (RuntimeException | ParseException ex) { - log.debug("sessionId", "idType", "id", ExceptionUtils.getStackTrace(ex)); - throw new InvalidDateTimeFormatException(ErrorCodes.PRG_BOOK_RCI_031.getCode(), - ErrorMessages.INVALID_BOOKING_DATE_TIME.getMessage() + " found for preregistration id - " - + requestMap.get(RequestCodes.PRE_REGISTRAION_ID.getCode()), - null); - } - return true; - } - - /** - * This method is used to validate from date and to date params - * - * @param fromDate - * @param toDate - * @param format - * @return true or false - */ - public boolean validateFromDateAndToDate(String fromDate, String toDate, String format) { - log.info("sessionId", "idType", "id", "In validateDataSyncRequest method of datasync service util"); - - if (isNull(fromDate) || !ValidationUtil.parseDate(fromDate, format)) { - throw new InvalidDateTimeFormatException( - io.mosip.preregistration.core.errorcodes.ErrorCodes.PRG_CORE_REQ_019.getCode(), - io.mosip.preregistration.core.errorcodes.ErrorMessages.INVALID_DATE_TIME_FORMAT.getMessage(), null); - } else if (!isNull(toDate) && !ValidationUtil.parseDate(toDate, format)) { - throw new InvalidDateTimeFormatException( - io.mosip.preregistration.core.errorcodes.ErrorCodes.PRG_CORE_REQ_019.getCode(), - io.mosip.preregistration.core.errorcodes.ErrorMessages.INVALID_DATE_TIME_FORMAT.getMessage(), null); - } else if (!isNull(fromDate) && !isNull(toDate) - && ((LocalDate.parse(fromDate)).isAfter(LocalDate.parse(toDate)))) { - throw new InvalidDateTimeFormatException( - io.mosip.preregistration.core.errorcodes.ErrorCodes.PRG_CORE_REQ_020.getCode(), - io.mosip.preregistration.core.errorcodes.ErrorMessages.FROM_DATE_GREATER_THAN_TO_DATE.getMessage(), - null); - } - return true; - } - - public boolean isValidRegCenter(String regId) { - List regCenter = getRegCenterMasterData(regId); - Boolean isValidRegCenter = regCenter.stream().anyMatch(iterate -> iterate.getId().contains(regId)); - - if (!isValidRegCenter) { - throw new RecordNotFoundException(ErrorCodes.PRG_BOOK_RCI_035.getCode(), - ErrorMessages.REG_CENTER_ID_NOT_FOUND.getMessage()); - } - return true; - - } - - public MainResponseDTO getApplicationStatus(String applicationId) { - MainResponseDTO response = new MainResponseDTO<>(); - //String url = preRegResourceUrl + "/applications/status/" + applicationId; - UriComponentsBuilder builder = UriComponentsBuilder - .fromUriString(preRegResourceUrl + "/applications/status/" + applicationId); - String uriBuilder = builder.build().encode().toUriString(); - HttpHeaders headers = new HttpHeaders(); - HttpEntity entity = new HttpEntity<>(headers); - log.info("sessionId", "idType", "id", "In call to prereg rest service :" + uriBuilder); - try { - ResponseEntity> responseEntity = restTemplate.exchange(uriBuilder, HttpMethod.GET, entity, - new ParameterizedTypeReference>() { - }); - MainResponseDTO body = responseEntity.getBody(); - if (body != null) { - if (body.getErrors() != null && !body.getErrors().isEmpty()) { - response.setErrors(body.getErrors()); - } else { - String applicationStatus = body.getResponse(); - if (applicationStatus != null) { - response.setResponse(applicationStatus); - } else { - response.setResponse(""); - } - } - } - log.info("sessionId", "idType", "id", "In call to demographic rest service :" + uriBuilder); - } catch (Exception ex) { - log.debug("Rest call exception " + ExceptionUtils.getStackTrace(ex)); - throw new RestClientException("rest call failed"); - } - return response; - } - -// public MainResponseDTO updatePreRegistrationStatus(String preRegId, String status) { -// MainResponseDTO response = new MainResponseDTO<>(); -// String url = preRegResourceUrl + "/applications/status/" + preRegId; -// MultiValueMap paramStatus = new LinkedMultiValueMap<>(); -// paramStatus.add("statusCode", status); -// HttpHeaders headers = new HttpHeaders(); -// HttpEntity entity = new HttpEntity<>(paramStatus, headers); -// System.out.println(url); -// log.info("sessionId", "idType", "id", "In call to demographic rest service :" + url); -// try { -// ResponseEntity> responseEntity = restTemplate.exchange(url, HttpMethod.PUT, entity, -// new ParameterizedTypeReference>() { -// }); -// if (responseEntity.getBody().getErrors() != null && !responseEntity.getBody().getErrors().isEmpty()) { -// response.setErrors(responseEntity.getBody().getErrors()); -// } else { -// response.setResponse(responseEntity.getBody().getResponse()); -// } -// -// log.info("sessionId", "idType", "id", "In call to demographic rest service :" + url); -// } catch (Exception ex) { -// log.debug("sessionId", "idType", "id", -// "demographic rest call exception " + ExceptionUtils.getStackTrace(ex)); -// throw new RestClientException("rest call failed"); -// } -// return response; -// } - -} - diff --git a/pre-registration-booking-service/src/main/resources/.gitignore b/pre-registration-booking-service/src/main/resources/.gitignore deleted file mode 100644 index c37fa0c4b35..00000000000 --- a/pre-registration-booking-service/src/main/resources/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/application.properties diff --git a/pre-registration-booking-service/src/main/resources/application-local.properties b/pre-registration-booking-service/src/main/resources/application-local.properties deleted file mode 100644 index ea26f93e49b..00000000000 --- a/pre-registration-booking-service/src/main/resources/application-local.properties +++ /dev/null @@ -1,168 +0,0 @@ -# Local profile for pre-registration-booking-service (run-local.sh / run-local.bat). -# Activate with: -Dspring.profiles.active=local -# Cluster Docker does not set this profile; it uses bootstrap + config-server env. -# No config-server, authmanager, or PostgreSQL required. H2 is in-memory. - -server.port=9095 -server.servlet.context-path=/preregistration/v1 -application.env.local=true - -spring.http.converters.preferred-json-mapper=jackson2 - -# Boot 4 local run (no config-server) -spring.cloud.config.enabled=false -spring.cloud.config.fail-fast=false -spring.config.import=optional:configserver: -health.config.enabled=false -management.health.config.enabled=false -management.endpoint.health.show-details=always -management.endpoints.web.exposure.include=info,health,refresh -spring.info.git.location=classpath:service-git.properties - -# Auth adapter (offline; do not point issuer at localhost or a Eureka service name) -mosip.auth.adapter.impl.basepackage=io.mosip.kernel.auth.defaultadapter -auth.server.admin.offline.token.validate=true -auth.server.validate.url=http://127.0.0.1:8091/authmanager/authorize/validateToken -auth.role.prefix=ROLE_ -auth.header.name=Authorization -spring.security.method-security.enabled=false -spring.mvc.pathmatch.matching-strategy=ant_path_matcher -mosip.global.end-points=/** -mosip.service.end-points=/** -mosip.kernel.auth.appids.realm.map={prereg:'preregistration'} -mosip.iam.adapter.clientid=mosip-prereg-client -mosip.iam.adapter.clientsecret=local -mosip.iam.adapter.appid=prereg -prereg.auth.jwt.secret=Yn2kjibddFAWtnPJ2AFlL8WXmohJMCvigQggaEypa5E= -mosip.security.authentication.provider.beans.list.pre-registration-booking-service=customJWTAuthProvider - -# H2: entities live in schema prereg. INIT creates it before Hibernate ddl-auto. -spring.datasource.url=jdbc:h2:mem:booking;DB_CLOSE_DELAY=-1;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;INIT=CREATE SCHEMA IF NOT EXISTS prereg -spring.datasource.driver-class-name=org.h2.Driver -spring.datasource.username=sa -spring.datasource.password= -spring.jpa.hibernate.ddl-auto=update -spring.jpa.properties.hibernate.hbm2ddl.create_namespaces=true -spring.jpa.show-sql=false -javax.persistence.jdbc.driver=org.h2.Driver -javax.persistence.jdbc.url=jdbc:h2:mem:booking;DB_CLOSE_DELAY=-1;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;INIT=CREATE SCHEMA IF NOT EXISTS prereg -javax.persistence.jdbc.user=sa -javax.persistence.jdbc.password= -hibernate.hbm2ddl.auto=update - -mosip.prereg.pii.backward.compatibility=true -mosip.utc-datetime-pattern=yyyy-MM-dd'T'HH:mm:ss.SSS'Z' -version=1.0 -id=mosip.pre-registration.booking.book -mosip.preregistration.booking.id.book=mosip.pre-registration.booking.book -mosip.id.preregistration.booking.book=mosip.pre-registration.booking.book -mosip.preregistration.booking.availability.sync.id=mosip.preregistration.booking.availability.sync -mosip.preregistration.booking.fetch.booking.id=mosip.preregistration.booking.fetch.booking -mosip.preregistration.booking.cancel.id=mosip.preregistration.booking.cancel -mosip.preregistration.booking.delete.id=mosip.preregistration.booking.delete -mosip.preregistration.booking.fetch.availability.id=mosip.preregistration.booking.fetch.availability -mosip.preregistration.booking.fetchPreidByDate.id=mosip.preregistration.booking.fetchPreidByDate -mosip.preregistration.booking.availability.increase.id=mosip.preregistration.booking.availability.increase -mosip.preregistration.booking.availability.check.id=mosip.preregistration.booking.availability.check -mosip.preregistration.booking.delete.old.id=mosip.preregistration.booking.delete.old -mosip.preregistration.booking.exception.id=mosip.preregistration.booking.parse.exception - -preregistration.availability.sync=7 -preregistration.availability.noOfDays=7 -preregistration.booking.offset=2 -preregistration.timespan.cancel=24 -preregistration.timespan.rebook=24 -preregistration.rebook.timespan=24 -preregistration.cancel.timespan=24 - -regCenter.url=http://127.0.0.1:8086/masterdata/v1.0/registrationcenters -holiday.url=http://127.0.0.1:8086/masterdata/v1.0/getregistrationcenterholidays/ -demographic.resource.url=http://127.0.0.1:9092/pre-registration/v1.0/applications -booking.resource.url=http://127.0.0.1:9095/preregistration/v1 -documentUrl=http://127.0.0.1:9093/demographic/v0.1/getDocument -mosip.io.prid.url=http://127.0.0.1:8100/v1/pridgenerator/prid -service.version=v1.0 -master.service.env=masterdata -demographic.service.env=demographic -demographic.service.version=v0.1 -document.service.env=demographic -document.service.version=v0.1 -notification.url=http://127.0.0.1:8083/v1/notifier/notify -resource.template.url=http://127.0.0.1:8086/masterdata/v1.0/templates -cryptoResource.url=http://127.0.0.1:8097/cryptomanager/v1.0 -audit.url=http://127.0.0.1:8098/auditmanager/v1.0/audits -emailResourse.url=http://127.0.0.1:8083/v1/notifier/email/send -smsResourse.url=http://127.0.0.1:8083/v1/notifier/sms/send -mosip.notification.timezone=GMT+05:30 -mosip.supported-languages=eng,ara,fra -mosip.primary-language=eng -mosip.mandatory-languages=eng -mosip.optional-languages=ara,fra - -preregistration.crypto.referenceId=INDIVIDUAL -preregistration.crypto.PrependThumbprint=false -preregistration.crypto.applicationId=PRE_REGISTRATION - -mosip.kernel.objectstore.account-name=prereg -cancel.appoinment.template=cancel-appointment -email.acknowledgement.template=Email-Acknowledgement -email.acknowledgement.subject.template=Acknowledgement-email-subject -sms.acknowledgement.template=SMS-Acknowledgement -cancel.appointment.email.subject=cancel-appointment-email-subject -noOfKiosks=10 -prereg_id.length=16 -preregistration.preid.regex=+[0-9] -timeSpanCheckForRebook=24 -timeSpanCheckForCancel=24 -mosip.kernel.prid.length=14 -mosip.kernel.prid.sequence-limit=3 -mosip.kernel.prid.repeating-block-limit=3 -mosip.kernel.prid.repeating-limit=2 -mosip.kernel.prid.not-start-with=0,1 -mosip.kernel.prid.restricted-numbers=786,666 -mosip.postal.code.length=6 -mosip.mobile.length=10 -mosip.email.length=50 -mosip.CINE.length=30 -auth-token-generator.rest.issuerUrl=http://127.0.0.1:8091 - -# ValidationUtil / idobjectvalidator (pre-registration-core) -mosip.kernel.idobjectvalidator.masterdata.documenttypes.rest.uri=http://127.0.0.1:8086/v1/masterdata/documenttypes/{documentcategorycode}/{langcode} -mosip.kernel.masterdata.validdoc.rest.uri=http://127.0.0.1:8086/v1/masterdata/validdocuments -mosip.id.validation.identity.dateOfBirth= -mosip.id.validation.identity.phone= -mosip.id.validation.identity.email= -mosip.id.validation.identity.postalCode= -mosip.id.validation.identity.CNIENumber= -mosip.id.validation.identity.phone.length=10 -mosip.id.validation.identity.email.length=50 -mosip.id.validation.identity.postalCode.length=6 -mosip.id.validation.identity.CNIENumber.length=30 - -mosip.role.preregistration.getappointmentavailability=INDIVIDUAL,PRE_REGISTRATION_ADMIN -mosip.role.preregistration.postappointmentpreregistrationid=INDIVIDUAL,PRE_REGISTRATION_ADMIN -mosip.role.preregistration.postappointment=INDIVIDUAL,PRE_REGISTRATION_ADMIN -mosip.role.preregistration.getappointmentpreregistrationid=INDIVIDUAL,PRE_REGISTRATION_ADMIN -mosip.role.preregistration.putappointmentpreregistrationid=INDIVIDUAL,PRE_REGISTRATION_ADMIN -mosip.role.preregistration.putbatchappointmentpreregistrationid=INDIVIDUAL,PRE_REGISTRATION_ADMIN -mosip.role.preregistration.deleteappointment=INDIVIDUAL,PRE_REGISTRATION_ADMIN -mosip.role.preregistration.getappointmentpreregistrationidregistrationcenterid=INDIVIDUAL,PRE_REGISTRATION_ADMIN -mosip.role.preregistration.getappointmentregistrationcenterid=INDIVIDUAL,PRE_REGISTRATION_ADMIN - -openapi.info.title=Pre-Registration-Booking -openapi.info.description=Pre-Registration-Booking Service -openapi.info.version=1.0 -openapi.info.license.name=Mosip -openapi.info.license.url=https://docs.mosip.io/platform/license -openapi.service.servers[0].url=${server.servlet.context-path} -openapi.service.servers[0].description=Pre-Registration-Booking Service -openapi.group.name=${openapi.info.title} -openapi.group.paths[0]=/** -springdoc.swagger-ui.disable-swagger-default-url=true -springdoc.swagger-ui.tagsSorter=alpha -springdoc.swagger-ui.operationsSorter=alpha -springdoc.swagger-ui.syntaxHighlight.activated=false -springdoc.swagger-ui.validator-url=none -springdoc.swagger-ui.persistAuthorization=true -springdoc.swagger-ui.path=/appointment/booking-service/swagger-ui.html -springdoc.api-docs.path=/appointment/booking-service/v3/api-docs diff --git a/pre-registration-booking-service/src/main/resources/bootstrap.properties b/pre-registration-booking-service/src/main/resources/bootstrap.properties deleted file mode 100644 index ef802362bd9..00000000000 --- a/pre-registration-booking-service/src/main/resources/bootstrap.properties +++ /dev/null @@ -1,54 +0,0 @@ -spring.cloud.config.uri=localhost -spring.cloud.config.label=master -spring.cloud.config.name=pre-registration -spring.application.name=pre-registration-booking-service -spring.profiles.active=dev -management.endpoint.health.show-details=always -management.endpoints.web.exposure.include=info,health,refresh -# Actuator /info reads this file. git.properties is reserved for kernel-core. -spring.info.git.location=classpath:service-git.properties - -server.servlet.context-path=/preregistration/v1 - -server.port=9095 - -##disabling health check so that client doesnt try to load properties from sprint config server every -## 5 minutes (should not be done in production) -health.config.enabled=false -mosip.preregistration.booking.id.book=mosip.pre-registration.booking.book -mosip.id.preregistration.booking.book=mosip.pre-registration.booking.book -## Not read by booking itself. Kept as a packaged default because booking's -## component scan loads app-service beans, six of which @Value this key with no -## fallback - dropping it would make booking startup depend on the config server. -mosip.prereg.pii.backward.compatibility=true - -#disabling health check so that client doesnt try to load properties from sprint config server every -# 5 minutes (should not be done in production) -#mosip.auth.adapter.impl.basepackage=io.mosip.kernel.auth.defaultadapter -mosip.id.validation.identity.phone=^([6-9]{1})([0-9]{9})$ -mosip.id.validation.identity.email: ^[\w-\+]+(\.[\w]+)*@[\w-]+(\.[\w]+)*(\.[a-zA-Z]{2,})$ - -prereg.auth.jwt.secret=Yn2kjibddFAWtnPJ2AFlL8WXmohJMCvigQggaEypa5E= - -openapi.info.title=Pre-Registration-Booking -openapi.info.description=Pre-Registration-Booking Service -openapi.info.version=1.0 -openapi.info.license.name=Mosip -openapi.info.license.url=https://docs.mosip.io/platform/license -# Relative server URL so Try-it-out uses the browser host (gateway), same as kernel-config-server. -openapi.service.servers[0].url=${server.servlet.context-path} -openapi.service.servers[0].description=Pre-Registration-Booking Service -openapi.group.name=${openapi.info.title} -openapi.group.paths[0]=/** -springdoc.swagger-ui.disable-swagger-default-url=true -springdoc.swagger-ui.tagsSorter=alpha -springdoc.swagger-ui.operationsSorter=alpha -springdoc.swagger-ui.syntaxHighlight.activated=false -springdoc.swagger-ui.validator-url=none -springdoc.swagger-ui.persistAuthorization=true -springdoc.swagger-ui.path=/appointment/booking-service/swagger-ui.html -springdoc.api-docs.path=/appointment/booking-service/v3/api-docs - -#the custom auth provider component names list -#this will be used by default auth adapter -mosip.security.authentication.provider.beans.list.pre-registration-booking-service=customJWTAuthProvider \ No newline at end of file diff --git a/pre-registration-booking-service/src/main/resources/logback.xml b/pre-registration-booking-service/src/main/resources/logback.xml deleted file mode 100644 index b9dfc23e616..00000000000 --- a/pre-registration-booking-service/src/main/resources/logback.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/pre-registration-booking-service/src/test/java/io/mosip/preregistration/booking/config/BookingApplicationComponentScanTest.java b/pre-registration-booking-service/src/test/java/io/mosip/preregistration/booking/config/BookingApplicationComponentScanTest.java deleted file mode 100644 index ffe91ff2099..00000000000 --- a/pre-registration-booking-service/src/test/java/io/mosip/preregistration/booking/config/BookingApplicationComponentScanTest.java +++ /dev/null @@ -1,63 +0,0 @@ -package io.mosip.preregistration.booking.config; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; -import java.util.List; - -import org.junit.Test; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.persistence.autoconfigure.EntityScan; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; - -import io.mosip.kernel.dataaccess.hibernate.repository.impl.HibernateRepositoryImpl; -import io.mosip.preregistration.booking.BookingApplication; - -/** - * Same pattern as kernel-notification-service {@code NotificationBootApplication}: - * allow-list {@code scanBasePackages} instead of {@code io.mosip.*}, and - * {@code excludeName} for kernel-core sidecar auto-configs. DataSource/JPA stay - * enabled because booking persists slots. - */ -public class BookingApplicationComponentScanTest { - - @Test - public void scanBasePackagesIsAllowListNotIoMosipStar() { - List packages = Arrays.asList( - BookingApplication.class.getAnnotation(SpringBootApplication.class).scanBasePackages()); - assertFalse(packages.contains("io.mosip.*")); - assertTrue(packages.contains("io.mosip.preregistration.booking.*")); - assertTrue(packages.contains("io.mosip.preregistration.core.*")); - assertTrue(packages.contains("${mosip.auth.adapter.impl.basepackage}")); - assertTrue(packages.contains("io.mosip.kernel.core.logger.config")); - assertTrue(packages.contains("io.mosip.kernel.idobjectvalidator.*")); - } - - @Test - public void jpaScanIncludesBookingAndCoreRepositoriesAndEntities() { - List repositories = Arrays.asList( - BookingApplication.class.getAnnotation(EnableJpaRepositories.class).basePackages()); - assertTrue(repositories.contains("io.mosip.preregistration.booking.repository")); - assertTrue(repositories.contains("io.mosip.preregistration.core.common.repository")); - assertEquals(HibernateRepositoryImpl.class, - BookingApplication.class.getAnnotation(EnableJpaRepositories.class).repositoryBaseClass()); - - List entities = Arrays.asList( - BookingApplication.class.getAnnotation(EntityScan.class).basePackages()); - assertTrue(entities.contains("io.mosip.preregistration.booking.entity")); - assertTrue(entities.contains("io.mosip.preregistration.core.common.entity")); - } - - @Test - public void autoConfigurationExcludesKernelCoreSidecarsNotDataSource() { - List names = Arrays.asList( - BookingApplication.class.getAnnotation(EnableAutoConfiguration.class).excludeName()); - assertTrue(names.contains("io.mosip.kernel.idgenerator.vid.impl.VidGeneratorImpl")); - assertTrue(names.contains("io.mosip.kernel.websub.api.config.WebSubClientConfig")); - assertFalse(names.contains("org.springframework.boot.jdbc.autoconfigure.DataSourceAutoConfiguration")); - assertFalse(names.contains("org.springframework.boot.hibernate.autoconfigure.HibernateJpaAutoConfiguration")); - } -} diff --git a/pre-registration-booking-service/src/test/java/io/mosip/preregistration/booking/config/BookingConfigOpenApiTest.java b/pre-registration-booking-service/src/test/java/io/mosip/preregistration/booking/config/BookingConfigOpenApiTest.java deleted file mode 100644 index 9050201afe4..00000000000 --- a/pre-registration-booking-service/src/test/java/io/mosip/preregistration/booking/config/BookingConfigOpenApiTest.java +++ /dev/null @@ -1,56 +0,0 @@ -package io.mosip.preregistration.booking.config; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; - -import java.util.List; - -import org.junit.Test; -import org.springframework.test.util.ReflectionTestUtils; - -import io.swagger.v3.oas.models.OpenAPI; -import io.swagger.v3.oas.models.security.SecurityScheme; - -/** - * Swagger UI Authorize is an OpenAPI header apiKey named Authorization. - */ -public class BookingConfigOpenApiTest { - - @Test - public void openApiRegistersAuthorizationHeaderApiKey() { - BookingConfig config = new BookingConfig(); - ReflectionTestUtils.setField(config, "openApiProperties", sampleProperties()); - - OpenAPI api = config.openApi(); - SecurityScheme scheme = api.getComponents().getSecuritySchemes().get(BookingConfig.AUTHORIZATION_SCHEME); - - assertNotNull(scheme); - assertEquals(SecurityScheme.Type.APIKEY, scheme.getType()); - assertEquals(SecurityScheme.In.HEADER, scheme.getIn()); - assertEquals(BookingConfig.AUTHORIZATION_SCHEME, scheme.getName()); - assertFalse(api.getSecurity().isEmpty()); - assertEquals(BookingConfig.AUTHORIZATION_SCHEME, api.getSecurity().get(0).keySet().iterator().next()); - assertEquals("/preregistration/v1", api.getServers().get(0).getUrl()); - } - - private static OpenApiProperties sampleProperties() { - LicenseProperty license = new LicenseProperty(); - license.setName("Mosip"); - license.setUrl("https://docs.mosip.io/platform/license"); - InfoProperty info = new InfoProperty(); - info.setTitle("Pre-Registration-Booking"); - info.setDescription("Pre-Registration-Booking Service"); - info.setVersion("1.0"); - info.setLicense(license); - Server server = new Server(); - server.setUrl("/preregistration/v1"); - server.setDescription("Pre-Registration-Booking Service"); - Service service = new Service(); - service.setServers(List.of(server)); - OpenApiProperties properties = new OpenApiProperties(); - properties.setInfo(info); - properties.setService(service); - return properties; - } -} diff --git a/pre-registration-booking-service/src/test/java/io/mosip/preregistration/booking/test/BookingApplicationTest.java b/pre-registration-booking-service/src/test/java/io/mosip/preregistration/booking/test/BookingApplicationTest.java deleted file mode 100644 index 6bc237edcbc..00000000000 --- a/pre-registration-booking-service/src/test/java/io/mosip/preregistration/booking/test/BookingApplicationTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package io.mosip.preregistration.booking.test; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication( - scanBasePackages = { "io.mosip.preregistration.core.*", "io.mosip.preregistration.booking.*" }, - excludeName = { - "org.springframework.boot.jdbc.autoconfigure.DataSourceAutoConfiguration", - "org.springframework.boot.hibernate.autoconfigure.HibernateJpaAutoConfiguration" - }) -public class BookingApplicationTest { - - /** - * Main method for Booking Application. - * - * @param args - * the arguments. - */ - public static void main(String[] args) { - SpringApplication.run(BookingApplicationTest.class, args); - } -} diff --git a/pre-registration-booking-service/src/test/java/io/mosip/preregistration/booking/test/config/TestConfig.java b/pre-registration-booking-service/src/test/java/io/mosip/preregistration/booking/test/config/TestConfig.java deleted file mode 100644 index b124c76179e..00000000000 --- a/pre-registration-booking-service/src/test/java/io/mosip/preregistration/booking/test/config/TestConfig.java +++ /dev/null @@ -1,43 +0,0 @@ -package io.mosip.preregistration.booking.test.config; - -import java.security.KeyManagementException; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.X509Certificate; - -import javax.net.ssl.SSLContext; - -import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; -import org.apache.hc.client5.http.impl.classic.HttpClients; -import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder; -import org.apache.hc.client5.http.io.HttpClientConnectionManager; -import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory; -import org.apache.http.ssl.TrustStrategy; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; -import org.springframework.web.client.RestTemplate; - -@Configuration -public class TestConfig { - @Bean - public RestTemplate selfTokenRestTemplate() - throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException { - - TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true; - - SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom() - .loadTrustMaterial(null, acceptingTrustStrategy).build(); - - SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext); - - HttpClientConnectionManager connectionManager = PoolingHttpClientConnectionManagerBuilder.create() - .setSSLSocketFactory(csf).build(); - CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).build(); - HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); - - - requestFactory.setHttpClient(httpClient); - return new RestTemplate(requestFactory); - } -} diff --git a/pre-registration-booking-service/src/test/java/io/mosip/preregistration/booking/test/config/TestSecurityConfig.java b/pre-registration-booking-service/src/test/java/io/mosip/preregistration/booking/test/config/TestSecurityConfig.java deleted file mode 100644 index 0844e19fb5f..00000000000 --- a/pre-registration-booking-service/src/test/java/io/mosip/preregistration/booking/test/config/TestSecurityConfig.java +++ /dev/null @@ -1,89 +0,0 @@ -// package io.mosip.preregistration.booking.test.config; - -// import java.util.ArrayList; -// import java.util.Arrays; -// import java.util.List; - -// import jakarta.servlet.http.HttpServletResponse; - -// import org.springframework.context.annotation.Bean; -// import org.springframework.context.annotation.Configuration; -// import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; -// import org.springframework.security.config.annotation.web.builders.HttpSecurity; -// import org.springframework.security.config.annotation.web.builders.WebSecurity; -// import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -// import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -// import org.springframework.security.config.http.SessionCreationPolicy; -// import org.springframework.security.core.authority.SimpleGrantedAuthority; -// import org.springframework.security.core.userdetails.User; -// import org.springframework.security.core.userdetails.UserDetails; -// import org.springframework.security.core.userdetails.UserDetailsService; -// import org.springframework.security.provisioning.InMemoryUserDetailsManager; -// import org.springframework.security.web.AuthenticationEntryPoint; -// import org.springframework.security.web.firewall.DefaultHttpFirewall; -// import org.springframework.security.web.firewall.HttpFirewall; - -// @Configuration -// @EnableWebSecurity -// @EnableGlobalMethodSecurity(prePostEnabled = true) -// @Order(2) -// @EnableMethodSecurity -// public class TestSecurityConfig @EnableGlobalMethodSecurity(prePostEnabled = true){ - - - - -// @Bean -// public HttpFirewall defaultHttpFirewall() { -// return new DefaultHttpFirewall(); -// } - -// @Override -// public void configure(WebSecurity webSecurity) throws Exception { -// webSecurity.ignoring().antMatchers(allowedEndPoints()); -// super.configure(webSecurity); -// webSecurity.httpFirewall(defaultHttpFirewall()); -// } - -// private String[] allowedEndPoints() { -// return new String[] { "/assets/**", "/icons/**", "/screenshots/**", "/favicon**", "/**/favicon**", "/css/**", -// "/js/**", "/*/error**", "/*/webjars/**", "/*/v2/api-docs", "/*/configuration/ui", -// "/*/configuration/security", "/*/swagger-resources/**", "/*/swagger-ui.html" }; -// } - -// @Override -// protected void configure(final HttpSecurity httpSecurity) throws Exception { -// httpSecurity.csrf().disable(); -// httpSecurity.httpBasic().and().authorizeRequests().anyRequest().authenticated().and().sessionManagement() -// .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().exceptionHandling() -// .authenticationEntryPoint(unauthorizedEntryPoint()); -// } - -// @Bean -// public AuthenticationEntryPoint unauthorizedEntryPoint() { -// return (request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED); -// } - -// @Bean -// protected SecurityFilterChain configureSecurityFilterChain(final HttpSecurity httpSecurity) throws Exception { -// return httpSecurity.build(); -// } - -// @Bean -// public UserDetailsService userDetailsService() { -// List users = new ArrayList<>(); -// users.add(new User("reg-officer", "mosip", -// Arrays.asList(new SimpleGrantedAuthority("ROLE_REGISTRATION_OFFICER")))); -// users.add(new User("reg-supervisor", "mosip", -// Arrays.asList(new SimpleGrantedAuthority("ROLE_REGISTRATION_SUPERVISOR")))); -// users.add(new User("reg-admin", "mosip", Arrays.asList(new SimpleGrantedAuthority("ROLE_REGISTRATION_ADMIN")))); -// users.add(new User("reg-processor", "mosip", -// Arrays.asList(new SimpleGrantedAuthority("ROLE_REGISTRATION_PROCESSOR")))); -// users.add(new User("id-auth", "mosip", Arrays.asList(new SimpleGrantedAuthority("ROLE_ID_AUTHENTICATION")))); -// users.add(new User("individual", "mosip", Arrays.asList(new SimpleGrantedAuthority("ROLE_INDIVIDUAL")))); -// users.add(new User("test", "mosip", Arrays.asList(new SimpleGrantedAuthority("ROLE_TEST")))); -// users.add(new User("PRE_REGISTRATION_ADMIN", "mosip", Arrays.asList(new SimpleGrantedAuthority("ROLE_PRE_REGISTRATION_ADMIN")))); -// return new InMemoryUserDetailsManager(users); -// } - -// } diff --git a/pre-registration-booking-service/src/test/java/io/mosip/preregistration/booking/test/controller/BookingControllerTest.java b/pre-registration-booking-service/src/test/java/io/mosip/preregistration/booking/test/controller/BookingControllerTest.java deleted file mode 100644 index 4e1fb14f956..00000000000 --- a/pre-registration-booking-service/src/test/java/io/mosip/preregistration/booking/test/controller/BookingControllerTest.java +++ /dev/null @@ -1,175 +0,0 @@ -package io.mosip.preregistration.booking.test.controller; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.validation.BeanPropertyBindingResult; -import org.springframework.validation.Errors; -import org.springframework.web.bind.WebDataBinder; - -import io.mosip.preregistration.booking.controller.BookingController; -import io.mosip.preregistration.booking.dto.AvailabilityDto; -import io.mosip.preregistration.booking.dto.BookingDataByRegIdDto; -import io.mosip.preregistration.booking.dto.BookingRequestDTO; -import io.mosip.preregistration.booking.dto.BookingStatus; -import io.mosip.preregistration.booking.dto.BookingStatusDTO; -import io.mosip.preregistration.booking.dto.MultiBookingRequest; -import io.mosip.preregistration.booking.service.BookingServiceIntf; -import io.mosip.preregistration.core.common.dto.BookingRegistrationDTO; -import io.mosip.preregistration.core.common.dto.CancelBookingResponseDTO; -import io.mosip.preregistration.core.common.dto.DeleteBookingDTO; -import io.mosip.preregistration.core.common.dto.MainRequestDTO; -import io.mosip.preregistration.core.common.dto.MainResponseDTO; -import io.mosip.preregistration.core.common.dto.PreRegIdsByRegCenterIdResponseDTO; -import io.mosip.preregistration.core.util.RequestValidator; - -@RunWith(MockitoJUnitRunner.class) -public class BookingControllerTest { - - private static final String PRE_ID = "98765432101234"; - private static final String CENTER_ID = "10001"; - private static final String FROM = "2026-12-01"; - private static final String TO = "2026-12-10"; - - @Mock - private BookingServiceIntf bookingService; - - @Mock - private RequestValidator requestValidator; - - @InjectMocks - private BookingController controller; - - private Errors errors; - - @Before - public void setUp() { - errors = new BeanPropertyBindingResult(new MainRequestDTO<>(), "request"); - } - - @Test - public void initBinderRegistersRequestValidator() { - WebDataBinder binder = org.mockito.Mockito.mock(WebDataBinder.class); - controller.initBinder(binder); - verify(binder).addValidators(requestValidator); - } - - @Test - public void getAvailabilityDelegatesToService() { - MainResponseDTO body = new MainResponseDTO<>(); - when(bookingService.getAvailability(CENTER_ID)).thenReturn(body); - - ResponseEntity> response = controller.getAvailability(CENTER_ID); - - assertEquals(HttpStatus.OK, response.getStatusCode()); - assertSame(body, response.getBody()); - } - - @Test - public void bookAppointmentValidatesIdThenDelegates() { - MainRequestDTO request = new MainRequestDTO<>(); - request.setId("book"); - MainResponseDTO body = new MainResponseDTO<>(); - when(bookingService.bookAppointment(request, PRE_ID)).thenReturn(body); - - ResponseEntity> response = controller.bookAppoinment(PRE_ID, request, errors); - - verify(requestValidator).validateId(eq("book"), eq("book"), any(Errors.class)); - assertEquals(HttpStatus.OK, response.getStatusCode()); - assertSame(body, response.getBody()); - } - - @Test - public void bookMultiAppointmentValidatesIdThenDelegates() { - MainRequestDTO request = new MainRequestDTO<>(); - request.setId("book"); - MainResponseDTO body = new MainResponseDTO<>(); - when(bookingService.bookMultiAppointment(request)).thenReturn(body); - - ResponseEntity> response = controller.bookMultiAppoinment(request, errors); - - verify(requestValidator).validateId(eq("book"), eq("book"), any(Errors.class)); - assertEquals(HttpStatus.OK, response.getStatusCode()); - assertSame(body, response.getBody()); - } - - @Test - public void getAppointmentsDelegatesToService() { - MainResponseDTO body = new MainResponseDTO<>(); - when(bookingService.getAppointmentDetails(PRE_ID)).thenReturn(body); - - ResponseEntity> response = controller.getAppointments(PRE_ID); - - assertEquals(HttpStatus.OK, response.getStatusCode()); - assertSame(body, response.getBody()); - } - - @Test - public void cancelBookDelegatesToService() { - MainResponseDTO body = new MainResponseDTO<>(); - when(bookingService.cancelAppointment(PRE_ID)).thenReturn(body); - - ResponseEntity> response = controller.cancelBook(PRE_ID); - - assertEquals(HttpStatus.OK, response.getStatusCode()); - assertSame(body, response.getBody()); - } - - @Test - public void cancelAppointmentBatchDelegatesToService() { - MainResponseDTO body = new MainResponseDTO<>(); - when(bookingService.cancelAppointmentBatch(PRE_ID)).thenReturn(body); - - ResponseEntity> response = controller.cancelAppointmentBatch(PRE_ID); - - assertEquals(HttpStatus.OK, response.getStatusCode()); - assertSame(body, response.getBody()); - } - - @Test - public void discardIndividualDelegatesToService() { - MainResponseDTO body = new MainResponseDTO<>(); - when(bookingService.deleteBooking(PRE_ID)).thenReturn(body); - - ResponseEntity> response = controller.discardIndividual(PRE_ID); - - assertEquals(HttpStatus.OK, response.getStatusCode()); - assertSame(body, response.getBody()); - } - - @Test - public void getBookedDataByDateDelegatesToService() { - MainResponseDTO body = new MainResponseDTO<>(); - when(bookingService.getBookedPreRegistrationByDate(FROM, TO, CENTER_ID)).thenReturn(body); - - ResponseEntity> response = controller.getBookedDataByDate( - FROM, TO, CENTER_ID); - - assertEquals(HttpStatus.OK, response.getStatusCode()); - assertSame(body, response.getBody()); - } - - @Test - public void getBookedDataByRegIdDelegatesToService() { - MainResponseDTO body = new MainResponseDTO<>(); - when(bookingService.getBookedPreRegistrations(FROM, TO, CENTER_ID)).thenReturn(body); - - ResponseEntity> response = controller.getBookedDataByRegId(FROM, TO, - CENTER_ID); - - assertEquals(HttpStatus.OK, response.getStatusCode()); - assertSame(body, response.getBody()); - } -} diff --git a/pre-registration-booking-service/src/test/java/io/mosip/preregistration/booking/test/service/BookingServiceCoverageTest.java b/pre-registration-booking-service/src/test/java/io/mosip/preregistration/booking/test/service/BookingServiceCoverageTest.java deleted file mode 100644 index 68ca591f5f7..00000000000 --- a/pre-registration-booking-service/src/test/java/io/mosip/preregistration/booking/test/service/BookingServiceCoverageTest.java +++ /dev/null @@ -1,594 +0,0 @@ -package io.mosip.preregistration.booking.test.service; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyMap; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.time.LocalDate; -import java.time.LocalTime; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.List; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Spy; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.test.util.ReflectionTestUtils; - -import io.mosip.kernel.core.authmanager.authadapter.model.AuthUserDetails; -import io.mosip.preregistration.booking.dto.AvailabilityDto; -import io.mosip.preregistration.booking.dto.BookingDataByRegIdDto; -import io.mosip.preregistration.booking.dto.BookingRequestDTO; -import io.mosip.preregistration.booking.dto.BookingStatus; -import io.mosip.preregistration.booking.dto.BookingStatusDTO; -import io.mosip.preregistration.booking.dto.MultiBookingRequest; -import io.mosip.preregistration.booking.dto.MultiBookingRequestDTO; -import io.mosip.preregistration.booking.dto.RegistrationCenterDto; -import io.mosip.preregistration.booking.entity.AvailibityEntity; -import io.mosip.preregistration.booking.errorcodes.ErrorCodes; -import io.mosip.preregistration.booking.errorcodes.ErrorMessages; -import io.mosip.preregistration.booking.exception.AvailablityNotFoundException; -import io.mosip.preregistration.booking.exception.DemographicGetStatusException; -import io.mosip.preregistration.booking.exception.RecordNotFoundException; -import io.mosip.preregistration.booking.repository.impl.BookingDAO; -import io.mosip.preregistration.booking.service.BookingService; -import io.mosip.preregistration.booking.service.util.BookingLock; -import io.mosip.preregistration.booking.service.util.BookingServiceUtil; -import io.mosip.preregistration.core.code.StatusCodes; -import io.mosip.preregistration.core.common.dto.BookingRegistrationDTO; -import io.mosip.preregistration.core.common.dto.CancelBookingResponseDTO; -import io.mosip.preregistration.core.common.dto.MainRequestDTO; -import io.mosip.preregistration.core.common.dto.MainResponseDTO; -import io.mosip.preregistration.core.common.dto.PreRegIdsByRegCenterIdResponseDTO; -import io.mosip.preregistration.core.common.entity.RegistrationBookingEntity; -import io.mosip.preregistration.core.common.service.ApplicationIdentityMigrationService; -import io.mosip.preregistration.core.exception.PreRegistrationException; -import io.mosip.preregistration.core.util.AuditLogUtil; -import io.mosip.preregistration.core.util.ValidationUtil; - -@RunWith(MockitoJUnitRunner.Silent.class) -public class BookingServiceCoverageTest { - - private static final String PRE_ID = "98765432101234"; - private static final String CENTER_ID = "10001"; - private static final String REG_DATE = "2026-12-10"; - private static final String FROM = "09:00"; - private static final String TO = "09:15"; - - @Mock - private BookingDAO bookingDAO; - - @Mock - private BookingServiceUtil serviceUtil; - - @Mock - private ApplicationIdentityMigrationService applicationIdentityMigrationService; - - @Mock - private ValidationUtil validationUtil; - - @Mock - private AuditLogUtil auditLogUtil; - - @Spy - private BookingLock bookingLock = new BookingLock(); - - @InjectMocks - private BookingService bookingService; - - private BookingRequestDTO bookingRequestDTO; - private AvailibityEntity availabilityEntity; - private RegistrationBookingEntity bookingEntity; - private AuthUserDetails principal; - - @Before - public void setUp() { - ReflectionTestUtils.setField(bookingService, "syncDays", 7); - ReflectionTestUtils.setField(bookingService, "displayDays", 7L); - ReflectionTestUtils.setField(bookingService, "availabilityOffset", 2); - ReflectionTestUtils.setField(bookingService, "versionUrl", "1.0"); - ReflectionTestUtils.setField(bookingService, "idUrlSync", "sync"); - ReflectionTestUtils.setField(bookingService, "idUrlBookAppointment", "book"); - ReflectionTestUtils.setField(bookingService, "idUrlFetch", "fetch"); - ReflectionTestUtils.setField(bookingService, "idUrlCancel", "cancel"); - ReflectionTestUtils.setField(bookingService, "idUrlDelete", "delete"); - ReflectionTestUtils.setField(bookingService, "idUrlAvailability", "availability"); - ReflectionTestUtils.setField(bookingService, "idUrlBookingByDate", "booking-by-date"); - ReflectionTestUtils.setField(bookingService, "idUrlIncreaseAvailability", "increase"); - ReflectionTestUtils.setField(bookingService, "idUrlCheckSlotAvailability", "check-slot"); - ReflectionTestUtils.setField(bookingService, "idUrlDeleteOld", "delete-old"); - - principal = org.mockito.Mockito.mock(AuthUserDetails.class); - when(principal.getUserId()).thenReturn("user-1"); - when(principal.getUsername()).thenReturn("user-1"); - SecurityContextHolder.getContext() - .setAuthentication(new UsernamePasswordAuthenticationToken(principal, null)); - - when(serviceUtil.getCurrentResponseTime()).thenReturn("2026-09-29T00:00:00.000Z"); - - bookingRequestDTO = new BookingRequestDTO(); - bookingRequestDTO.setRegistrationCenterId(CENTER_ID); - bookingRequestDTO.setRegDate(REG_DATE); - bookingRequestDTO.setSlotFromTime(FROM); - bookingRequestDTO.setSlotToTime(TO); - - availabilityEntity = new AvailibityEntity(); - availabilityEntity.setRegcntrId(CENTER_ID); - availabilityEntity.setRegDate(LocalDate.parse(REG_DATE)); - availabilityEntity.setFromTime(LocalTime.parse(FROM)); - availabilityEntity.setToTime(LocalTime.parse(TO)); - availabilityEntity.setAvailableKiosks(5); - - bookingEntity = new RegistrationBookingEntity(); - bookingEntity.setCrBy("creator"); - bookingEntity.setPreregistrationId(PRE_ID); - bookingEntity.setRegistrationCenterId(CENTER_ID); - bookingEntity.setRegDate(LocalDate.parse(REG_DATE)); - bookingEntity.setSlotFromTime(LocalTime.parse(FROM)); - bookingEntity.setSlotToTime(LocalTime.parse(TO)); - } - - @After - public void tearDown() { - SecurityContextHolder.clearContext(); - } - - @Test - public void setupBookingServiceIsNoOp() { - bookingService.setupBookingService(); - } - - @Test - public void authUserDetailsReturnsPrincipal() { - assertEquals(principal, bookingService.authUserDetails()); - } - - @Test - public void getAvailabilityReturnsSlots() { - when(serviceUtil.isValidRegCenter(CENTER_ID)).thenReturn(true); - when(bookingDAO.findAvailability(eq(CENTER_ID), any(LocalDate.class), any(LocalDate.class))) - .thenReturn(List.of(availabilityEntity)); - when(serviceUtil.slotSetter(any(), any(), any(), any())).thenReturn(0); - - MainResponseDTO response = bookingService.getAvailability(CENTER_ID); - - assertEquals(CENTER_ID, response.getResponse().getRegCenterId()); - assertEquals("availability", response.getId()); - verify(auditLogUtil).saveAuditDetails(any()); - } - - @Test - public void getAvailabilityHolidayLookaheadThenEmpty() { - when(serviceUtil.isValidRegCenter(CENTER_ID)).thenReturn(true); - when(bookingDAO.findAvailability(eq(CENTER_ID), any(LocalDate.class), any(LocalDate.class))) - .thenReturn(List.of(availabilityEntity)).thenReturn(null); - when(serviceUtil.slotSetter(any(), any(), any(), any())).thenReturn(2); - - MainResponseDTO response = bookingService.getAvailability(CENTER_ID); - - assertEquals(CENTER_ID, response.getResponse().getRegCenterId()); - verify(bookingDAO, org.mockito.Mockito.times(2)).findAvailability(eq(CENTER_ID), any(LocalDate.class), - any(LocalDate.class)); - } - - @Test - public void getAvailabilityHolidayLookaheadFindsMoreSlots() { - AvailibityEntity nextDay = new AvailibityEntity(); - nextDay.setRegcntrId(CENTER_ID); - nextDay.setRegDate(LocalDate.parse("2026-12-11")); - nextDay.setFromTime(LocalTime.parse(FROM)); - nextDay.setToTime(LocalTime.parse(TO)); - nextDay.setAvailableKiosks(3); - - when(serviceUtil.isValidRegCenter(CENTER_ID)).thenReturn(true); - when(bookingDAO.findAvailability(eq(CENTER_ID), any(LocalDate.class), any(LocalDate.class))) - .thenReturn(List.of(availabilityEntity)).thenReturn(List.of(nextDay)); - when(serviceUtil.slotSetter(any(), any(), any(), any())).thenReturn(1).thenReturn(0); - - MainResponseDTO response = bookingService.getAvailability(CENTER_ID); - - assertNotNull(response.getResponse().getCenterDetails()); - } - - @Test(expected = RecordNotFoundException.class) - public void getAvailabilityThrowsWhenNoSlots() { - when(serviceUtil.isValidRegCenter(CENTER_ID)).thenReturn(true); - when(bookingDAO.findAvailability(eq(CENTER_ID), any(LocalDate.class), any(LocalDate.class))).thenReturn(null); - - bookingService.getAvailability(CENTER_ID); - } - - @Test - public void bookAppointmentPendingAppointmentCreatesBooking() { - stubSuccessfulBookPath(StatusCodes.PENDING_APPOINTMENT.getCode()); - - MainResponseDTO response = bookingService.bookAppointment(mainBookingRequest(), PRE_ID); - - assertEquals("Appointment booked successfully", response.getResponse().getBookingMessage()); - verify(bookingDAO).saveRegistrationEntityForBooking(any()); - } - - @Test - public void bookAppointmentCancelledCreatesBooking() { - stubSuccessfulBookPath(StatusCodes.CANCELLED.getCode()); - - MainResponseDTO response = bookingService.bookAppointment(mainBookingRequest(), PRE_ID); - - assertEquals("Appointment booked successfully", response.getResponse().getBookingMessage()); - } - - @Test - public void bookAppointmentBookedRebooks() { - stubSuccessfulBookPath(StatusCodes.BOOKED.getCode()); - when(bookingDAO.findByPreRegistrationId(PRE_ID)).thenReturn(bookingEntity); - when(bookingDAO.deleteByPreRegistrationId(PRE_ID)).thenReturn(1); - when(bookingDAO.findByRegDateAndRegcntrIdAndFromTimeAndToTime(any(), anyString(), any(), any())) - .thenReturn(availabilityEntity); - when(serviceUtil.timeSpanCheckForRebook(any(), any())).thenReturn(true); - - MainResponseDTO response = bookingService.bookAppointment(mainBookingRequest(), PRE_ID); - - assertEquals("Appointment booked successfully", response.getResponse().getBookingMessage()); - verify(bookingDAO, org.mockito.Mockito.atLeastOnce()).deleteByPreRegistrationId(PRE_ID); - } - - @Test - public void bookAppointmentExpiredDeletesThenBooks() { - stubSuccessfulBookPath(StatusCodes.EXPIRED.getCode()); - when(bookingDAO.deleteByPreRegistrationId(PRE_ID)).thenReturn(1); - - MainResponseDTO response = bookingService.bookAppointment(mainBookingRequest(), PRE_ID); - - assertEquals("Appointment booked successfully", response.getResponse().getBookingMessage()); - } - - @Test(expected = DemographicGetStatusException.class) - public void bookAppointmentRejectsIncompleteApplication() { - when(serviceUtil.validateAppointmentDate(anyMap())).thenReturn(true); - when(serviceUtil.getApplicationBookingStatus(PRE_ID)) - .thenReturn(StatusCodes.APPLICATION_INCOMPLETE.getCode()); - - bookingService.bookAppointment(mainBookingRequest(), PRE_ID); - } - - @Test(expected = DemographicGetStatusException.class) - public void bookAppointmentRejectsPrefetchedApplication() { - when(serviceUtil.validateAppointmentDate(anyMap())).thenReturn(true); - when(serviceUtil.getApplicationBookingStatus(PRE_ID)).thenReturn(StatusCodes.PREFETCHED.getCode()); - - bookingService.bookAppointment(mainBookingRequest(), PRE_ID); - } - - @Test - public void bookAppointmentSkipsWhenDateInvalid() { - when(serviceUtil.validateAppointmentDate(anyMap())).thenReturn(false); - - MainResponseDTO response = bookingService.bookAppointment(mainBookingRequest(), PRE_ID); - - verify(bookingDAO, never()).saveRegistrationEntityForBooking(any()); - assertNotNull(response); - } - - @Test - public void bookMultiAppointmentPendingAppointment() { - stubSuccessfulBookPath(StatusCodes.PENDING_APPOINTMENT.getCode()); - - MainResponseDTO response = bookingService.bookMultiAppointment(multiBookingRequest()); - - assertEquals(1, response.getResponse().getBookingStatusResponse().size()); - } - - @Test - public void bookMultiAppointmentBookedRebooks() { - stubSuccessfulBookPath(StatusCodes.BOOKED.getCode()); - when(bookingDAO.findByPreRegistrationId(PRE_ID)).thenReturn(bookingEntity); - when(bookingDAO.deleteByPreRegistrationId(PRE_ID)).thenReturn(1); - when(bookingDAO.findByRegDateAndRegcntrIdAndFromTimeAndToTime(any(), anyString(), any(), any())) - .thenReturn(availabilityEntity); - when(serviceUtil.timeSpanCheckForRebook(any(), any())).thenReturn(true); - - MainResponseDTO response = bookingService.bookMultiAppointment(multiBookingRequest()); - - assertEquals(1, response.getResponse().getBookingStatusResponse().size()); - } - - @Test - public void bookMultiAppointmentExpiredDeletesThenBooks() { - stubSuccessfulBookPath(StatusCodes.EXPIRED.getCode()); - when(bookingDAO.deleteByPreRegistrationId(PRE_ID)).thenReturn(1); - - MainResponseDTO response = bookingService.bookMultiAppointment(multiBookingRequest()); - - assertEquals(1, response.getResponse().getBookingStatusResponse().size()); - } - - @Test - public void bookMultiAppointmentCancelledCreatesBooking() { - stubSuccessfulBookPath(StatusCodes.CANCELLED.getCode()); - - MainResponseDTO response = bookingService.bookMultiAppointment(multiBookingRequest()); - - assertEquals(1, response.getResponse().getBookingStatusResponse().size()); - } - - @Test(expected = DemographicGetStatusException.class) - public void bookMultiAppointmentRejectsIncomplete() { - when(serviceUtil.validateAppointmentDate(anyMap())).thenReturn(true); - when(serviceUtil.getApplicationBookingStatus(PRE_ID)) - .thenReturn(StatusCodes.APPLICATION_INCOMPLETE.getCode()); - - bookingService.bookMultiAppointment(multiBookingRequest()); - } - - @Test(expected = DemographicGetStatusException.class) - public void bookMultiAppointmentRejectsPrefetched() { - when(serviceUtil.validateAppointmentDate(anyMap())).thenReturn(true); - when(serviceUtil.getApplicationBookingStatus(PRE_ID)).thenReturn(StatusCodes.PREFETCHED.getCode()); - - bookingService.bookMultiAppointment(multiBookingRequest()); - } - - @Test - public void getAppointmentDetailsReturnsSlot() { - when(serviceUtil.checkApplicationStatus(PRE_ID)).thenReturn(true); - when(bookingDAO.findByPreRegistrationId(PRE_ID)).thenReturn(bookingEntity); - - MainResponseDTO response = bookingService.getAppointmentDetails(PRE_ID); - - assertEquals(CENTER_ID, response.getResponse().getRegistrationCenterId()); - assertEquals(REG_DATE, response.getResponse().getRegDate()); - } - - @Test(expected = PreRegistrationException.class) - public void getAppointmentDetailsRejectsBlankId() { - bookingService.getAppointmentDetails(" "); - } - - @Test(expected = PreRegistrationException.class) - public void getAppointmentDetailsRejectsNullId() { - bookingService.getAppointmentDetails(null); - } - - @Test - public void cancelAppointmentWrapsCancelBooking() { - stubCancelSuccess(false); - - MainResponseDTO response = bookingService.cancelAppointment(PRE_ID); - - assertTrue(response.getResponse().getMessage().contains("cancelled")); - assertEquals("cancel", response.getId()); - } - - @Test - public void cancelAppointmentBatchSkipsTimeSpanCheck() { - stubCancelSuccess(true); - - MainResponseDTO response = bookingService.cancelAppointmentBatch(PRE_ID); - - assertTrue(response.getResponse().getMessage().contains("cancelled")); - verify(serviceUtil, never()).timeSpanCheckForCancle(any()); - } - - @Test - public void checkSlotAvailabilitySucceedsWhenKioskOpen() { - RegistrationCenterDto center = new RegistrationCenterDto(); - center.setId(CENTER_ID); - when(serviceUtil.getRegCenterMasterData(CENTER_ID)).thenReturn(List.of(center)); - when(bookingDAO.findRegistrationCenterId(CENTER_ID)).thenReturn(true); - when(bookingDAO.findByRegDateAndRegcntrIdAndFromTimeAndToTime(any(), anyString(), any(), any())) - .thenReturn(availabilityEntity); - - bookingService.checkSlotAvailability(bookingRequestDTO); - - verify(bookingDAO).findRegistrationCenterId(CENTER_ID); - } - - @Test(expected = RecordNotFoundException.class) - public void checkSlotAvailabilityRejectsUnknownCenter() { - RegistrationCenterDto other = new RegistrationCenterDto(); - other.setId("99999"); - when(serviceUtil.getRegCenterMasterData(CENTER_ID)).thenReturn(List.of(other)); - - bookingService.checkSlotAvailability(bookingRequestDTO); - } - - @Test(expected = AvailablityNotFoundException.class) - public void checkSlotAvailabilityRejectsEmptySlot() { - RegistrationCenterDto center = new RegistrationCenterDto(); - center.setId(CENTER_ID); - availabilityEntity.setAvailableKiosks(0); - when(serviceUtil.getRegCenterMasterData(CENTER_ID)).thenReturn(List.of(center)); - when(bookingDAO.findRegistrationCenterId(CENTER_ID)).thenReturn(true); - when(bookingDAO.findByRegDateAndRegcntrIdAndFromTimeAndToTime(any(), anyString(), any(), any())) - .thenReturn(availabilityEntity); - - bookingService.checkSlotAvailability(bookingRequestDTO); - } - - @Test - public void deleteOldBookingReturnsTrueWhenRowsDeleted() { - when(bookingDAO.deleteByPreRegistrationId(PRE_ID)).thenReturn(2); - - assertTrue(bookingService.deleteOldBooking(PRE_ID)); - } - - @Test - public void deleteOldBookingReturnsFalseWhenNothingDeleted() { - when(bookingDAO.deleteByPreRegistrationId(PRE_ID)).thenReturn(0); - - assertFalse(bookingService.deleteOldBooking(PRE_ID)); - } - - @Test(expected = RecordNotFoundException.class) - public void deleteOldBookingRethrowsMappedException() { - when(bookingDAO.deleteByPreRegistrationId(PRE_ID)) - .thenThrow(new RecordNotFoundException(ErrorCodes.PRG_BOOK_RCI_015.getCode(), - ErrorMessages.NO_TIME_SLOTS_ASSIGNED_TO_THAT_REG_CENTER.getMessage())); - - bookingService.deleteOldBooking(PRE_ID); - } - - @Test - public void increaseAvailabilityIncrementsKioskCount() { - when(bookingDAO.findByRegDateAndRegcntrIdAndFromTimeAndToTime(any(), anyString(), any(), any())) - .thenReturn(availabilityEntity); - when(bookingDAO.updateAvailibityEntity(any())).thenReturn(availabilityEntity); - - assertTrue(bookingService.increaseAvailability(bookingRequestDTO)); - assertEquals(6, availabilityEntity.getAvailableKiosks()); - } - - @Test(expected = RecordNotFoundException.class) - public void increaseAvailabilityRethrowsMappedException() { - when(bookingDAO.findByRegDateAndRegcntrIdAndFromTimeAndToTime(any(), anyString(), any(), any())) - .thenThrow(new RecordNotFoundException(ErrorCodes.PRG_BOOK_RCI_015.getCode(), - ErrorMessages.NO_TIME_SLOTS_ASSIGNED_TO_THAT_REG_CENTER.getMessage())); - - bookingService.increaseAvailability(bookingRequestDTO); - } - - @Test - public void setAuditValuesPersistsAudit() { - bookingService.setAuditValues("PRE_401", "RETRIEVE", "BUSINESS", "ok", "id-type", "user-1", "user-1", - CENTER_ID); - - verify(auditLogUtil).saveAuditDetails(any()); - } - - @Test - public void getBookedPreRegistrationByDateReturnsIds() { - when(serviceUtil.validateFromDateAndToDate(anyString(), anyString(), anyString())).thenReturn(true); - when(bookingDAO.findByBookingDateBetweenAndRegCenterId(any(), any(), eq(CENTER_ID), any())) - .thenReturn(List.of(PRE_ID)); - - MainResponseDTO response = bookingService - .getBookedPreRegistrationByDate("2026-12-01", "2026-12-10", CENTER_ID); - - assertEquals(List.of(PRE_ID), response.getResponse().getPreRegistrationIds()); - assertEquals(CENTER_ID, response.getResponse().getRegistrationCenterId()); - } - - @Test - public void getBookedPreRegistrationByDateDefaultsEmptyToDate() { - when(serviceUtil.validateFromDateAndToDate(eq("2026-12-01"), eq("2026-12-01"), anyString())).thenReturn(true); - when(bookingDAO.findByBookingDateBetweenAndRegCenterId(any(), any(), eq(CENTER_ID), any())) - .thenReturn(new ArrayList<>()); - - MainResponseDTO response = bookingService - .getBookedPreRegistrationByDate("2026-12-01", "", CENTER_ID); - - assertNotNull(response.getResponse()); - } - - @Test(expected = RecordNotFoundException.class) - public void getBookedPreRegistrationByDateRethrowsMappedException() { - when(serviceUtil.validateFromDateAndToDate(anyString(), anyString(), anyString())) - .thenThrow(new RecordNotFoundException(ErrorCodes.PRG_BOOK_RCI_015.getCode(), - ErrorMessages.NO_TIME_SLOTS_ASSIGNED_TO_THAT_REG_CENTER.getMessage())); - - bookingService.getBookedPreRegistrationByDate("2026-12-01", "2026-12-10", CENTER_ID); - } - - @Test - public void getBookedPreRegistrationsReturnsSlotsById() { - when(serviceUtil.validateFromDateAndToDate(anyString(), anyString(), anyString())).thenReturn(true); - when(bookingDAO.findByBookingDateBetweenAndRegCenterId(any(), any(), eq(CENTER_ID), any())) - .thenReturn(List.of(PRE_ID)); - - MainResponseDTO response = bookingService.getBookedPreRegistrations("2026-12-01", - "2026-12-10", CENTER_ID); - - assertEquals(CENTER_ID, response.getResponse().getRegistrationCenterId()); - assertNotNull(response.getResponse().getIdsWithAppointmentDate()); - } - - @Test - public void getBookedPreRegistrationsDefaultsNullToDate() { - when(serviceUtil.validateFromDateAndToDate(eq("2026-12-01"), eq("2026-12-01"), anyString())).thenReturn(true); - when(bookingDAO.findByBookingDateBetweenAndRegCenterId(any(), any(), eq(CENTER_ID), any())) - .thenReturn(Collections.emptyList()); - - MainResponseDTO response = bookingService.getBookedPreRegistrations("2026-12-01", null, - CENTER_ID); - - assertEquals(CENTER_ID, response.getResponse().getRegistrationCenterId()); - } - - @Test(expected = RecordNotFoundException.class) - public void getBookedPreRegistrationsRethrowsMappedException() { - when(serviceUtil.validateFromDateAndToDate(anyString(), anyString(), anyString())) - .thenThrow(new RecordNotFoundException(ErrorCodes.PRG_BOOK_RCI_015.getCode(), - ErrorMessages.NO_TIME_SLOTS_ASSIGNED_TO_THAT_REG_CENTER.getMessage())); - - bookingService.getBookedPreRegistrations("2026-12-01", "2026-12-10", CENTER_ID); - } - - private void stubSuccessfulBookPath(String statusCode) { - when(serviceUtil.validateAppointmentDate(anyMap())).thenReturn(true); - when(serviceUtil.getApplicationBookingStatus(PRE_ID)).thenReturn(statusCode); - when(serviceUtil.mandatoryParameterCheck(eq(PRE_ID), any())).thenReturn(true); - when(serviceUtil.slotTimeValidCheck(eq(PRE_ID), any())).thenReturn(true); - RegistrationCenterDto center = new RegistrationCenterDto(); - center.setId(CENTER_ID); - when(serviceUtil.getRegCenterMasterData(CENTER_ID)).thenReturn(List.of(center)); - when(bookingDAO.findRegistrationCenterId(CENTER_ID)).thenReturn(true); - when(bookingDAO.findByRegDateAndRegcntrIdAndFromTimeAndToTime(any(), anyString(), any(), any())) - .thenReturn(availabilityEntity); - when(bookingDAO.findFirstByRegDateAndRegcntrIdAndFromTimeAndToTime(any(), anyString(), any(), any())) - .thenReturn(availabilityEntity); - when(serviceUtil.isKiosksAvailable(any())).thenReturn(true); - when(serviceUtil.bookingEntitySetter(anyString(), any())).thenReturn(bookingEntity); - when(bookingDAO.saveRegistrationEntityForBooking(any())).thenReturn(bookingEntity); - when(bookingDAO.updateAvailibityEntity(any())).thenReturn(availabilityEntity); - } - - private void stubCancelSuccess(boolean batch) { - when(serviceUtil.mandatoryParameterCheckforCancel(PRE_ID)).thenReturn(true); - when(serviceUtil.getDemographicStatusForCancel(PRE_ID)).thenReturn(true); - when(bookingDAO.findByPreRegistrationId(PRE_ID)).thenReturn(bookingEntity); - when(bookingDAO.findFirstByRegDateAndRegcntrIdAndFromTimeAndToTime(any(), anyString(), any(), any())) - .thenReturn(availabilityEntity); - when(bookingDAO.updateAvailibityEntity(any())).thenReturn(availabilityEntity); - if (!batch) { - when(serviceUtil.timeSpanCheckForCancle(any())).thenReturn(true); - } - } - - private MainRequestDTO mainBookingRequest() { - MainRequestDTO request = new MainRequestDTO<>(); - request.setRequest(bookingRequestDTO); - request.setRequesttime(new Date()); - return request; - } - - private MainRequestDTO multiBookingRequest() { - MultiBookingRequestDTO row = new MultiBookingRequestDTO(); - row.setPreRegistrationId(PRE_ID); - row.setRegistrationCenterId(CENTER_ID); - row.setRegDate(REG_DATE); - row.setSlotFromTime(FROM); - row.setSlotToTime(TO); - MultiBookingRequest multi = new MultiBookingRequest(); - multi.setBookingRequest(List.of(row)); - MainRequestDTO request = new MainRequestDTO<>(); - request.setRequest(multi); - request.setRequesttime(new Date()); - return request; - } -} diff --git a/pre-registration-booking-service/src/test/java/io/mosip/preregistration/booking/test/service/BookingServiceIdentityMigrationTest.java b/pre-registration-booking-service/src/test/java/io/mosip/preregistration/booking/test/service/BookingServiceIdentityMigrationTest.java deleted file mode 100644 index 6b328b5efab..00000000000 --- a/pre-registration-booking-service/src/test/java/io/mosip/preregistration/booking/test/service/BookingServiceIdentityMigrationTest.java +++ /dev/null @@ -1,313 +0,0 @@ -package io.mosip.preregistration.booking.test.service; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyMap; -import static org.mockito.ArgumentMatchers.anyString; - -import java.time.LocalDate; -import java.time.LocalTime; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.context.SecurityContextHolder; - -import io.mosip.kernel.core.authmanager.authadapter.model.AuthUserDetails; -import io.mosip.preregistration.core.common.service.ApplicationIdentityMigrationService; -import io.mosip.preregistration.booking.dto.BookingRequestDTO; -import io.mosip.preregistration.booking.dto.BookingStatusDTO; -import io.mosip.preregistration.booking.entity.AvailibityEntity; -import io.mosip.preregistration.booking.repository.impl.BookingDAO; -import io.mosip.preregistration.booking.service.BookingService; -import io.mosip.preregistration.booking.service.util.BookingServiceUtil; -import io.mosip.preregistration.core.common.dto.CancelBookingResponseDTO; -import io.mosip.preregistration.core.common.dto.DeleteBookingDTO; -import io.mosip.preregistration.core.common.dto.MainResponseDTO; -import io.mosip.preregistration.core.common.entity.RegistrationBookingEntity; -import io.mosip.preregistration.core.util.AuditLogUtil; -import io.mosip.preregistration.core.util.ValidationUtil; - -/** - * Covers the best-effort contract of the canonical-identity backfill invoked - * from {@link BookingService}. - * - *

The backfill rewrites legacy raw identifiers to canonical UUIDs and is - * documented as best-effort: it must never fail the user's request, because the - * booking's own {@code crBy} is already canonical by the time it runs, and any - * record it misses is swept up by the nightly identity reconciliation job. The - * call sites therefore swallow failures. Without that guard the exception - * reaches {@code BookingExceptionCatcher}, which rethrows, and the whole booking - * is rolled back - which is exactly what these tests pin down. - */ -@RunWith(MockitoJUnitRunner.Silent.class) -public class BookingServiceIdentityMigrationTest { - - private static final String PRE_REG_ID = "98765432101234"; - - private static final String CANONICAL_CR_BY = "3f2a9c14-7b6d-4e18-9c53-1d8ef04a25b7"; - - private static final String BOOKING_SUCCESS_MESSAGE = "Appointment booked successfully"; - - @Mock - private BookingDAO bookingDAO; - - @Mock - private BookingServiceUtil serviceUtil; - - @Mock - private ApplicationIdentityMigrationService applicationIdentityMigrationService; - - @Mock - private ValidationUtil validationUtil; - - @Mock - private AuditLogUtil auditLogUtil; - - @InjectMocks - private BookingService bookingService; - - private BookingRequestDTO bookingRequestDTO; - - private AvailibityEntity availabilityEntity; - - private RegistrationBookingEntity bookingEntity; - - @Before - public void setUp() { - bookingRequestDTO = new BookingRequestDTO(); - bookingRequestDTO.setRegistrationCenterId("10001"); - bookingRequestDTO.setRegDate("2026-12-10"); - bookingRequestDTO.setSlotFromTime("09:00"); - bookingRequestDTO.setSlotToTime("09:15"); - - availabilityEntity = new AvailibityEntity(); - availabilityEntity.setRegcntrId("10001"); - availabilityEntity.setRegDate(LocalDate.parse("2026-12-10")); - availabilityEntity.setFromTime(LocalTime.parse("09:00")); - availabilityEntity.setToTime(LocalTime.parse("09:15")); - availabilityEntity.setAvailableKiosks(5); - - bookingEntity = new RegistrationBookingEntity(); - bookingEntity.setCrBy(CANONICAL_CR_BY); - bookingEntity.setPreregistrationId(PRE_REG_ID); - bookingEntity.setRegistrationCenterId("10001"); - bookingEntity.setRegDate(LocalDate.parse("2026-12-10")); - bookingEntity.setSlotFromTime(LocalTime.parse("09:00")); - bookingEntity.setSlotToTime(LocalTime.parse("09:15")); - - Mockito.when(bookingDAO.findFirstByRegDateAndRegcntrIdAndFromTimeAndToTime(any(), anyString(), any(), any())) - .thenReturn(availabilityEntity); - Mockito.when(serviceUtil.isKiosksAvailable(any())).thenReturn(true); - Mockito.when(serviceUtil.bookingEntitySetter(anyString(), any())).thenReturn(bookingEntity); - Mockito.when(bookingDAO.saveRegistrationEntityForBooking(any())).thenReturn(bookingEntity); - Mockito.when(bookingDAO.updateAvailibityEntity(any())).thenReturn(availabilityEntity); - } - - private void givenIdentityMigrationFails() { - Mockito.doThrow(new RuntimeException("identity migration unavailable")) - .when(applicationIdentityMigrationService).migrateRawUserToEffectiveUser(anyString(), any()); - } - - /** - * A failing backfill must not surface to the applicant as a failed booking. - */ - @Test - public void book_identityMigrationFails_bookingSucceeds() { - givenIdentityMigrationFails(); - - BookingStatusDTO result = bookingService.book(PRE_REG_ID, bookingRequestDTO); - - assertNotNull(result); - assertEquals(BOOKING_SUCCESS_MESSAGE, result.getBookingMessage()); - } - - /** - * The steps after the backfill must still run. Guarding only the exception - * without letting the flow continue would leave the slot reserved but never - * decremented, so this asserts the side effect rather than just the response. - */ - @Test - public void book_identityMigrationFails_availabilityStillDecremented() { - givenIdentityMigrationFails(); - - bookingService.book(PRE_REG_ID, bookingRequestDTO); - - assertEquals(4, availabilityEntity.getAvailableKiosks()); - Mockito.verify(bookingDAO).updateAvailibityEntity(availabilityEntity); - } - - /** - * Guard must not change the happy path: the backfill is still invoked, and - * still with the booking's own canonical creator rather than the caller. - */ - @Test - public void book_identityMigrationSucceeds_migratesWithBookingCreator() { - BookingStatusDTO result = bookingService.book(PRE_REG_ID, bookingRequestDTO); - - assertEquals(BOOKING_SUCCESS_MESSAGE, result.getBookingMessage()); - Mockito.verify(applicationIdentityMigrationService).migrateRawUserToEffectiveUser(PRE_REG_ID, - CANONICAL_CR_BY); - } - - // --------------------------------------------------------------------- - // deleteBooking - // - // resolveEffectiveUserId throws a plain IllegalStateException, which - // BookingExceptionCatcher.handle() does not map - its final else rethrows - // only BaseUncheckedException / BaseCheckedException. An unguarded failure - // is therefore swallowed and the method returns a success-shaped response - // having never deleted anything. These tests pin the guard that prevents it. - // --------------------------------------------------------------------- - - private void givenDeleteBookingIsReachable() { - AuthUserDetails principal = Mockito.mock(AuthUserDetails.class); - Mockito.when(principal.getUserId()).thenReturn("test-user"); - Mockito.when(principal.getUsername()).thenReturn("test-user"); - SecurityContextHolder.getContext() - .setAuthentication(new UsernamePasswordAuthenticationToken(principal, null)); - - Mockito.when(validationUtil.requstParamValidator(anyMap())).thenReturn(true); - Mockito.when(serviceUtil.checkApplicationStatus(PRE_REG_ID)).thenReturn(true); - Mockito.when(bookingDAO.findByPreRegistrationId(PRE_REG_ID)).thenReturn(bookingEntity); - } - - private void givenIdentityResolutionFails() { - Mockito.when(applicationIdentityMigrationService.resolveEffectiveUserId(anyString())) - .thenThrow(new IllegalStateException("Failed to resolve UUID for user during migration")); - } - - @After - public void clearSecurityContext() { - SecurityContextHolder.clearContext(); - } - - /** - * The deletion is the caller's actual intent and must not be blocked by an - * unresolvable legacy identifier. - */ - @Test - public void deleteBooking_identityResolutionFails_bookingStillDeleted() { - givenDeleteBookingIsReachable(); - givenIdentityResolutionFails(); - - MainResponseDTO response = bookingService.deleteBooking(PRE_REG_ID); - - Mockito.verify(bookingDAO).deleteByPreRegistrationId(PRE_REG_ID); - assertNotNull(response.getResponse()); - assertEquals(PRE_REG_ID, response.getResponse().getPreRegistrationId()); - } - - /** - * Attribution degrades to absent. It must never fall back to the raw - * identifier, which would put plaintext PII back on the wire. - * - *

The sibling assertions matter: asserting only that {@code deletedBy} is - * null would also hold when the method aborts before setting anything, so the - * test would pass against the very defect it exists to catch. Requiring the - * rest of the DTO to be populated proves the flow ran to completion with just - * this one field omitted. - */ - @Test - public void deleteBooking_identityResolutionFails_deletedByOmitted() { - givenDeleteBookingIsReachable(); - givenIdentityResolutionFails(); - - MainResponseDTO response = bookingService.deleteBooking(PRE_REG_ID); - - assertNull(response.getResponse().getDeletedBy()); - assertEquals(PRE_REG_ID, response.getResponse().getPreRegistrationId()); - assertNotNull(response.getResponse().getDeletedDateTime()); - } - - /** - * Guard must not change the resolvable path. - */ - @Test - public void deleteBooking_identityResolutionSucceeds_deletedByPopulated() { - givenDeleteBookingIsReachable(); - Mockito.when(applicationIdentityMigrationService.resolveEffectiveUserId(CANONICAL_CR_BY)) - .thenReturn(CANONICAL_CR_BY); - - MainResponseDTO response = bookingService.deleteBooking(PRE_REG_ID); - - Mockito.verify(bookingDAO).deleteByPreRegistrationId(PRE_REG_ID); - assertEquals(CANONICAL_CR_BY, response.getResponse().getDeletedBy()); - } - - // --------------------------------------------------------------------- - // cancelBooking - // - // Here the resolve and the backfill are both inside the guard, because the - // resolved id is not used beyond the backfill call. A failure must leave the - // cancellation itself untouched. - // --------------------------------------------------------------------- - - private static final String CANCEL_SUCCESS_MESSAGE = - "Appointment for the selected application has been successfully cancelled"; - - private void givenCancelBookingIsReachable() { - AuthUserDetails principal = Mockito.mock(AuthUserDetails.class); - Mockito.when(principal.getUserId()).thenReturn("test-user"); - Mockito.when(principal.getUsername()).thenReturn("test-user"); - SecurityContextHolder.getContext() - .setAuthentication(new UsernamePasswordAuthenticationToken(principal, null)); - - Mockito.when(serviceUtil.mandatoryParameterCheckforCancel(PRE_REG_ID)).thenReturn(true); - Mockito.when(serviceUtil.getDemographicStatusForCancel(PRE_REG_ID)).thenReturn(true); - Mockito.when(bookingDAO.findByPreRegistrationId(PRE_REG_ID)).thenReturn(bookingEntity); - } - - /** - * The cancellation is the caller's intent; a failing backfill must not stop it. - */ - @Test - public void cancelBooking_identityMigrationFails_cancellationSucceeds() { - givenCancelBookingIsReachable(); - givenIdentityResolutionFails(); - - CancelBookingResponseDTO result = bookingService.cancelBooking(PRE_REG_ID, false); - - Mockito.verify(bookingDAO).deleteByPreRegistrationId(PRE_REG_ID); - assertEquals(CANCEL_SUCCESS_MESSAGE, result.getMessage()); - } - - /** - * Cancelling frees the slot again. Asserting the side effect catches a guard - * that swallows the exception but lets the flow skip the steps after it. - */ - @Test - public void cancelBooking_identityMigrationFails_availabilityStillRestored() { - givenCancelBookingIsReachable(); - givenIdentityResolutionFails(); - - bookingService.cancelBooking(PRE_REG_ID, false); - - assertEquals(6, availabilityEntity.getAvailableKiosks()); - Mockito.verify(bookingDAO).updateAvailibityEntity(availabilityEntity); - } - - /** - * Guard must not change the resolvable path. - */ - @Test - public void cancelBooking_identityResolutionSucceeds_migratesWithResolvedId() { - givenCancelBookingIsReachable(); - Mockito.when(applicationIdentityMigrationService.resolveEffectiveUserId(CANONICAL_CR_BY)) - .thenReturn(CANONICAL_CR_BY); - - CancelBookingResponseDTO result = bookingService.cancelBooking(PRE_REG_ID, false); - - assertEquals(CANCEL_SUCCESS_MESSAGE, result.getMessage()); - Mockito.verify(applicationIdentityMigrationService).migrateRawUserToEffectiveUser(PRE_REG_ID, - CANONICAL_CR_BY); - } -} diff --git a/pre-registration-booking-service/src/test/java/io/mosip/preregistration/booking/test/service/BookingServiceTest.java b/pre-registration-booking-service/src/test/java/io/mosip/preregistration/booking/test/service/BookingServiceTest.java deleted file mode 100644 index a07b8e7160d..00000000000 --- a/pre-registration-booking-service/src/test/java/io/mosip/preregistration/booking/test/service/BookingServiceTest.java +++ /dev/null @@ -1,1763 +0,0 @@ -package io.mosip.preregistration.booking.test.service; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.text.SimpleDateFormat; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.LocalTime; -import java.time.ZoneId; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.TimeZone; - -import org.json.simple.parser.JSONParser; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.bean.override.mockito.MockitoBean; -import org.springframework.core.ParameterizedTypeReference; -import org.springframework.http.HttpMethod; -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.test.context.junit4.SpringRunner; -import org.springframework.web.client.RestTemplate; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.kernel.core.authmanager.authadapter.model.AuthUserDetails; -import io.mosip.kernel.core.dataaccess.exception.DataAccessLayerException; -import io.mosip.kernel.core.exception.FileNotFoundException; -import io.mosip.kernel.core.exception.ParseException; -import io.mosip.kernel.core.idobjectvalidator.spi.IdObjectValidator; -import io.mosip.kernel.core.util.DateUtils2; -import io.mosip.preregistration.booking.codes.RequestCodes; -import io.mosip.preregistration.booking.dto.AvailabilityDto; -import io.mosip.preregistration.booking.dto.BookingRequestDTO; -import io.mosip.preregistration.booking.dto.BookingStatus; -import io.mosip.preregistration.booking.dto.BookingStatusDTO; -import io.mosip.preregistration.booking.dto.CancelBookingDTO; -import io.mosip.preregistration.booking.dto.DateTimeDto; -import io.mosip.preregistration.booking.dto.HolidayDto; -import io.mosip.preregistration.booking.dto.MultiBookingRequest; -import io.mosip.preregistration.booking.dto.MultiBookingRequestDTO; -import io.mosip.preregistration.booking.dto.RegistrationCenterDto; -import io.mosip.preregistration.booking.dto.RegistrationCenterHolidayDto; -import io.mosip.preregistration.booking.dto.RegistrationCenterResponseDto; -import io.mosip.preregistration.booking.dto.SlotDto; -import io.mosip.preregistration.booking.dto.SlotTimeDto; -import io.mosip.preregistration.booking.entity.AvailibityEntity; -import io.mosip.preregistration.booking.errorcodes.ErrorCodes; -import io.mosip.preregistration.booking.errorcodes.ErrorMessages; -import io.mosip.preregistration.booking.exception.AvailablityNotFoundException; -import io.mosip.preregistration.booking.exception.BookingDataNotFoundException; -import io.mosip.preregistration.booking.exception.RecordNotFoundException; -import io.mosip.preregistration.booking.exception.TimeSpanException; -import io.mosip.preregistration.booking.repository.BookingAvailabilityRepository; -import io.mosip.preregistration.booking.repository.RegistrationBookingRepository; -import io.mosip.preregistration.booking.repository.impl.BookingDAO; -import io.mosip.preregistration.booking.service.BookingService; -import io.mosip.preregistration.booking.service.BookingServiceIntf; -import io.mosip.preregistration.booking.service.util.BookingServiceUtil; -import io.mosip.preregistration.core.code.AuditLogVariables; -import io.mosip.preregistration.core.code.StatusCodes; -import io.mosip.preregistration.core.common.dto.AuditRequestDto; -import io.mosip.preregistration.core.common.dto.BookingRegistrationDTO; -import io.mosip.preregistration.core.common.dto.CancelBookingResponseDTO; -import io.mosip.preregistration.core.common.dto.DeleteBookingDTO; -import io.mosip.preregistration.core.common.dto.MainRequestDTO; -import io.mosip.preregistration.core.common.dto.MainResponseDTO; -import io.mosip.preregistration.core.common.dto.PreRegIdsByRegCenterIdDTO; -import io.mosip.preregistration.core.common.dto.PreRegIdsByRegCenterIdResponseDTO; -import io.mosip.preregistration.core.common.dto.PreRegistartionStatusDTO; -import io.mosip.preregistration.core.common.dto.ResponseWrapper; -import io.mosip.preregistration.core.common.entity.DemographicEntity; -import io.mosip.preregistration.core.common.entity.RegistrationBookingEntity; -import io.mosip.preregistration.core.common.entity.RegistrationBookingPK; -import io.mosip.preregistration.core.exception.InvalidRequestParameterException; -import io.mosip.preregistration.core.exception.RecordFailedToDeleteException; -import io.mosip.preregistration.core.exception.TableNotAccessibleException; -import io.mosip.preregistration.core.util.AuditLogUtil; -import io.mosip.preregistration.core.util.RequestValidator; -import io.mosip.preregistration.core.util.ValidationUtil; - -/** -* Booking service Test -* -* @author Kishan Rathore -* @author Tapaswini Behera -* @since 1.0.0 -**/ - -@RunWith(SpringRunner.class) -@SpringBootTest -@Ignore -public class BookingServiceTest { - - @MockitoBean - private BookingAvailabilityRepository bookingAvailabilityRepository; - - @MockitoBean - private RegistrationBookingRepository registrationBookingRepository; - - /** - * Mocking the RestTemplateBuilder bean - */ - - @MockitoBean(name = "selfTokenRestTemplate") - RestTemplate restTemplate; - - @MockitoBean - private SecurityContextHolder context; - - @MockitoBean - private RequestValidator requestValidator; - - @MockitoBean - private AuditLogUtil auditLogUtil; - - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - - @InjectMocks - private BookingService service; - - @MockitoBean - private BookingServiceUtil serviceUtil; - - private DemographicEntity preRegistrationEntity; - - /** - * Mocking the JsonValidatorImpl bean - */ - @MockitoBean(name = "idObjectValidator") - private IdObjectValidator jsonValidator; - - @Autowired - private ValidationUtil validationUtil; - - @MockitoBean - ObjectMapper mapper; - - @MockitoBean - private BookingDAO bookingDAO; - - AuditRequestDto auditRequestDto = new AuditRequestDto(); - - private AvailabilityDto availability = new AvailabilityDto(); - private List dateList = new ArrayList<>(); - private DateTimeDto dateDto = new DateTimeDto(); - private List slotsList = new ArrayList<>(); - - private SlotDto slots = new SlotDto(); - - AvailibityEntity availableEntity = new AvailibityEntity(); - RegistrationBookingEntity bookingEntity = new RegistrationBookingEntity(); - List statusList = new ArrayList<>(); - PreRegistartionStatusDTO preRegistartionStatusDTO = new PreRegistartionStatusDTO(); - @SuppressWarnings("rawtypes") - MainResponseDTO preRegResponse = new MainResponseDTO(); - - BookingRequestDTO bookingRequestDTO = new BookingRequestDTO(); - - BookingRequestDTO rebookingRequestDTO = new BookingRequestDTO(); - - BookingRegistrationDTO oldBooking = new BookingRegistrationDTO(); - BookingRegistrationDTO oldBooking_success = new BookingRegistrationDTO(); - BookingRegistrationDTO newBooking = new BookingRegistrationDTO(); - MainResponseDTO> responseDto = new MainResponseDTO<>(); - BookingStatusDTO statusDTOA = new BookingStatusDTO(); - BookingStatusDTO statusDTOB = new BookingStatusDTO(); - Map requiredRequestMap = new HashMap<>(); - InvalidRequestParameterException parameterException = null; - boolean requestValidatorFlag = false; - Map requestMap = new HashMap<>(); - - RegistrationCenterResponseDto regCenDto = new RegistrationCenterResponseDto(); - - Map requestMap1 = new HashMap<>(); - private MainRequestDTO cancelRequestdto = new MainRequestDTO<>(); - private CancelBookingDTO cancelbookingDto = new CancelBookingDTO(); - - DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); - LocalTime localTime1; - LocalTime localTime2; - PreRegIdsByRegCenterIdDTO preRegIdsByRegCenterIdDTO = new PreRegIdsByRegCenterIdDTO(); - List bookingEntities = new ArrayList<>(); - MainRequestDTO requestDTO = new MainRequestDTO<>(); - MainRequestDTO bookingDto = new MainRequestDTO<>(); - MainRequestDTO reBookingDto = new MainRequestDTO<>(); - - MultiBookingRequestDTO multiBookingRequestDto1 = new MultiBookingRequestDTO(); - MultiBookingRequestDTO multiBookingRequestDto2 = new MultiBookingRequestDTO(); - - List multiBookingListDto = new ArrayList<>(); - - @Value("${version}") - String versionUrl; - - @Value("${id}") - String idUrl; - - @Value("${demographic.resource.url}") - private String preRegResourceUrl; - - // Rebooking - String reBookingPreId = "23587986034785"; - // booking - String bookingPreId = "23587986034785"; - RegistrationCenterDto centerDto = new RegistrationCenterDto(); - List centerList = new ArrayList<>(); - - LocalTime startTime; - LocalTime endTime; - LocalTime perKioskTime; - LocalTime LunchStartTime; - LocalTime LunchEndTime; - - @SuppressWarnings("unchecked") - @Before - public void setup() throws URISyntaxException, FileNotFoundException, ParseException, java.io.FileNotFoundException, - IOException, org.json.simple.parser.ParseException { - MockitoAnnotations.initMocks(this); - LocalDateTime localDateTime1 = LocalDateTime.now(); - LocalDateTime localDateTime2 = localDateTime1.plusMinutes(15); - localTime1 = localDateTime1.toLocalTime(); - localTime2 = localDateTime2.toLocalTime(); - slots.setAvailability(4); - slots.setFromTime(localTime1); - slots.setToTime(localTime2); - slotsList.add(slots); - dateDto.setDate(LocalDate.now().toString()); - dateDto.setHoliday(false); - dateDto.setTimeSlots(slotsList); - dateList.add(dateDto); - availability.setCenterDetails(dateList); - availability.setRegCenterId("1"); - - startTime = localDateTime1.toLocalTime(); - endTime = localDateTime2.toLocalTime(); - perKioskTime = LocalTime.MIDNIGHT.plusMinutes(15); - LunchStartTime = LocalTime.NOON.plusHours(1); - LunchEndTime = LunchStartTime.plusHours(1); - - ClassLoader classLoader = getClass().getClassLoader(); - JSONParser parser = new JSONParser(); - - URI dataSyncUri = new URI( - classLoader.getResource("booking.json").getFile().trim().replaceAll("\\u0020", "%20")); - File file = new File(dataSyncUri.getPath()); - parser.parse(new FileReader(file)); - - oldBooking.setRegistrationCenterId("1"); - oldBooking.setSlotFromTime(LocalTime.of(9, 0).toString()); - oldBooking.setSlotToTime(LocalTime.of(9, 15).toString()); - oldBooking.setRegDate(LocalDate.now().toString()); - - newBooking.setRegistrationCenterId("1"); - newBooking.setSlotFromTime(LocalTime.of(9, 0).toString()); - newBooking.setSlotToTime(LocalTime.of(9, 15).toString()); - newBooking.setRegDate(LocalDate.now().plusDays(5).toString()); - - oldBooking_success.setRegistrationCenterId("1"); - oldBooking_success.setSlotFromTime("09:00"); - oldBooking_success.setSlotToTime("09:13"); - oldBooking_success.setRegDate("2019-12-05"); - - statusDTOA.setBookingMessage("Appointment booked successfully"); - - statusDTOB.setBookingMessage("Appointment booked successfully"); - - List resp = new ArrayList<>(); - mapper.setTimeZone(TimeZone.getDefault()); - resp.add(statusDTOA); - resp.add(statusDTOB); - responseDto.setResponse(resp); - responseDto.setErrors(null); - responseDto.setResponsetime(serviceUtil.getCurrentResponseTime()); - - - requiredRequestMap.put("id", idUrl); - requiredRequestMap.put("version", versionUrl); - - cancelRequestdto.setRequesttime(new Date()); - cancelRequestdto.setRequest(cancelbookingDto); - cancelRequestdto.setId("mosip.pre-registration.booking.book"); - cancelRequestdto.setVersion("1.0"); - cancelbookingDto.setRegDate(LocalDate.now().plusDays(30).toString()); - cancelbookingDto.setRegistrationCenterId("1"); - cancelbookingDto.setSlotFromTime(LocalTime.of(9, 0).toString()); - cancelbookingDto.setSlotToTime(LocalTime.of(9, 15).toString()); - requestMap1.put("id", cancelRequestdto.getId()); - requestMap1.put("version", cancelRequestdto.getVersion()); - requestMap1.put("reqTime", - new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").format(cancelRequestdto.getRequesttime())); - requestMap1.put("request", cancelRequestdto.getRequest().toString()); - - availableEntity.setAvailableKiosks(4); - availableEntity.setRegcntrId("1"); - availableEntity.setRegDate(LocalDate.now().plusDays(30)); - availableEntity.setToTime(localTime2); - availableEntity.setFromTime(localTime1); - availableEntity.setCrBy("John Doe"); - availableEntity.setCrDate(DateUtils2.parseDateToLocalDateTime(new Date())); - availableEntity.setDeleted(false); - preRegistrationEntity = new DemographicEntity(); - preRegistrationEntity.setCreateDateTime(LocalDateTime.now()); - preRegistrationEntity.setCreatedBy("John Doe"); - preRegistrationEntity.setStatusCode("Pending_Appointment"); - preRegistrationEntity.setUpdateDateTime(LocalDateTime.now()); - preRegistrationEntity.setPreRegistrationId("48690172097499"); - -// bookingEntity.setBookingPK(new RegistrationBookingPK(DateUtils2.parseDateToLocalDateTime(new Date())));bookingEntity.setRegistrationCenterId(oldBooking.getRegistrationCenterId());bookingEntity.setLangCode("12L");bookingEntity.setCrBy("John Doe");bookingEntity.setCrDate(DateUtils2.parseDateToLocalDateTime(new Date()));bookingEntity.setRegDate(LocalDate.parse(oldBooking.getRegDate()));bookingEntity.setSlotFromTime(LocalTime.parse(oldBooking.getSlotFromTime()));bookingEntity.setSlotToTime(LocalTime.parse(oldBooking.getSlotToTime()));bookingEntity.setDemographicEntity(preRegistrationEntity); - - preRegistartionStatusDTO.setStatusCode(StatusCodes.PENDING_APPOINTMENT.getCode()); - preRegistartionStatusDTO.setPreRegistartionId("23587986034785"); - statusList.add(preRegistartionStatusDTO); - - preRegResponse.setResponse(statusList); - preRegResponse.setErrors(null); - List preId = new ArrayList<>(); - preId.add("1234567890"); - preRegIdsByRegCenterIdDTO.setRegistrationCenterId("1"); - preRegIdsByRegCenterIdDTO.setPreRegistrationIds(preId); - requestDTO.setRequest(preRegIdsByRegCenterIdDTO); - - requestDTO.setId("mosip.preregistration.booking.book"); - requestDTO.setVersion("1.0"); - requestDTO.setRequesttime(new Date()); - bookingDto.setId("mosip.pre-registration.booking.book"); - bookingDto.setRequesttime(new Date()); - bookingDto.setVersion("1.0"); - - // Rebook - reBookingDto.setId("mosip.pre-registration.booking.book"); - reBookingDto.setRequesttime(new Date()); - reBookingDto.setVersion("1.0"); - - AuthUserDetails applicationUser = Mockito.mock(AuthUserDetails.class); - Authentication authentication = Mockito.mock(Authentication.class); - SecurityContext securityContext = Mockito.mock(SecurityContext.class); - Mockito.when(securityContext.getAuthentication()).thenReturn(authentication); - SecurityContextHolder.setContext(securityContext); - Mockito.when(SecurityContextHolder.getContext().getAuthentication().getPrincipal()).thenReturn(applicationUser); - auditRequestDto.setActionTimeStamp(LocalDateTime.now(ZoneId.of("UTC"))); - auditRequestDto.setApplicationId(AuditLogVariables.MOSIP_1.toString()); - auditRequestDto.setApplicationName(AuditLogVariables.PREREGISTRATION.toString()); - auditRequestDto.setCreatedBy(AuditLogVariables.SYSTEM.toString()); - auditRequestDto.setHostIp(auditLogUtil.getServerIp()); - auditRequestDto.setHostName(auditLogUtil.getServerName()); - auditRequestDto.setId(AuditLogVariables.NO_ID.toString()); - auditRequestDto.setIdType(AuditLogVariables.PRE_REGISTRATION_ID.toString()); - auditRequestDto.setSessionUserId(AuditLogVariables.SYSTEM.toString()); - auditRequestDto.setSessionUserName(AuditLogVariables.SYSTEM.toString()); - - // Get valid reg center list - centerDto.setId("1"); - centerDto.setLangCode("eng"); - centerDto.setCenterStartTime(startTime); - centerDto.setCenterEndTime(endTime); - centerDto.setPerKioskProcessTime(perKioskTime); - centerDto.setLunchStartTime(LunchStartTime); - centerDto.setLunchEndTime(LunchEndTime); - centerDto.setNumberOfKiosks((short) 4); - centerList.add(centerDto); - } - - @Test - public void getAvailabilityTest() { - - logger.info("Availability dto " + availability); - AvailibityEntity availableEntity1 = new AvailibityEntity(); - - availableEntity1.setAvailableKiosks(4); - availableEntity1.setRegcntrId("1"); - availableEntity1.setRegDate(LocalDate.now()); - availableEntity1.setToTime(localTime2); - availableEntity1.setFromTime(localTime1); - availableEntity1.setCrBy("John Doe"); - availableEntity1.setCrDate(DateUtils2.parseDateToLocalDateTime(new Date())); - availableEntity1.setDeleted(false); - List date = new ArrayList<>(); - List entityList = new ArrayList<>(); - date.add(LocalDate.now()); - entityList.add(availableEntity); - entityList.add(availableEntity1); - logger.info("Availability entity " + availableEntity); - - RegistrationCenterDto centerDto = new RegistrationCenterDto(); - List centerList = new ArrayList<>(); - centerDto.setId("10001"); - centerDto.setLangCode("eng"); - centerDto.setCenterStartTime(startTime); - centerDto.setCenterEndTime(endTime); - centerDto.setPerKioskProcessTime(perKioskTime); - centerDto.setLunchStartTime(LunchStartTime); - centerDto.setLunchEndTime(LunchEndTime); - centerDto.setNumberOfKiosks((short) 4); - centerList.add(centerDto); - regCenDto.setRegistrationCenters(centerList); - ResponseWrapper resp = new ResponseWrapper<>(); - resp.setResponse(regCenDto); - Mockito.when(bookingDAO.updateAvailibityEntity(availableEntity)).thenReturn(availableEntity); - Mockito.when(serviceUtil.mandatoryParameterCheck(Mockito.anyString(), Mockito.any())).thenReturn(true); - Mockito.when(serviceUtil.isValidRegCenter(Mockito.any())).thenReturn(true); - Mockito.when(serviceUtil.isKiosksAvailable(Mockito.any())).thenReturn(true); - Mockito.when(serviceUtil.getRegCenterMasterData("10001")).thenReturn(centerList); - Mockito.when(bookingDAO.findAvailability(Mockito.anyString(), Mockito.any(), Mockito.any())) - .thenReturn(entityList); - MainResponseDTO responseDto = service.getAvailability("10001"); - logger.info("Response " + responseDto); - assertEquals("10001", responseDto.getResponse().getRegCenterId()); - - } - - @Test(expected = RecordNotFoundException.class) - public void getAvailabilityFailureTest() { - RecordNotFoundException ex = new RecordNotFoundException(ErrorCodes.PRG_BOOK_RCI_035.getCode(), - ErrorMessages.REG_CENTER_ID_NOT_FOUND.getMessage()); - Mockito.when(serviceUtil.isValidRegCenter("1")).thenThrow(ex); - service.getAvailability("1"); - - } - - @SuppressWarnings("unchecked") - @Test - public void successBookAppointment() { - - MainRequestDTO bookingRequestDTOs = new MainRequestDTO<>(); - List successBookDtoList = new ArrayList<>(); - BookingRequestDTO successBookDto = new BookingRequestDTO(); - successBookDto.setRegistrationCenterId("1"); - successBookDto.setSlotFromTime(LocalTime.of(9, 0).toString()); - successBookDto.setSlotToTime(LocalTime.of(9, 15).toString()); - successBookDto.setRegDate(LocalDate.now().plusDays(30).toString()); - successBookDtoList.add(successBookDto); - bookingRequestDTOs.setId("mosip.preregistration.booking.book"); - bookingRequestDTOs.setVersion("1.0"); - bookingRequestDTOs.setRequesttime(new Date()); - bookingRequestDTOs.setRequest(successBookDto); - - availableEntity.setAvailableKiosks(3); - availableEntity.setRegcntrId("1"); - availableEntity.setRegDate(LocalDate.now().plusDays(30)); - availableEntity.setToTime(LocalTime.of(9, 0)); - availableEntity.setFromTime(LocalTime.of(9, 15)); - availableEntity.setCrBy("John Doe"); - availableEntity.setCrDate(DateUtils2.parseDateToLocalDateTime(new Date())); - availableEntity.setDeleted(false); - List statusListrebook = new ArrayList<>(); - - PreRegistartionStatusDTO preRegistartionStatus = new PreRegistartionStatusDTO(); - preRegistartionStatus.setStatusCode(StatusCodes.BOOKED.getCode()); - preRegistartionStatus.setPreRegistartionId(bookingPreId); - preRegResponse.setResponse(preRegistartionStatus); - statusListrebook.add(preRegistartionStatus); - MainResponseDTO preRegResponseRebook = new MainResponseDTO(); - preRegResponseRebook.setErrors(null); - preRegResponseRebook.setResponse(preRegistartionStatus); - Mockito.when(bookingDAO.findByRegDateAndRegcntrIdAndFromTimeAndToTime(Mockito.any(), Mockito.any(), - Mockito.any(), Mockito.any())).thenReturn(availableEntity); - - requestValidatorFlag = validationUtil.requestValidator(bookingRequestDTOs); - Mockito.when(bookingDAO.updateAvailibityEntity(availableEntity)).thenReturn(availableEntity); - Mockito.when(serviceUtil.mandatoryParameterCheck(Mockito.anyString(), Mockito.any())).thenReturn(true); - Mockito.when(serviceUtil.validateAppointmentDate(Mockito.any())).thenReturn(true); - Mockito.when(serviceUtil.isKiosksAvailable(Mockito.any())).thenReturn(true); - Mockito.when(serviceUtil.getApplicationBookingStatus(Mockito.anyString())).thenReturn("Booked"); - Mockito.when(serviceUtil.getRegCenterMasterData("1")).thenReturn(centerList); - // Update status - RegistrationBookingEntity bookingEntity2 = new RegistrationBookingEntity(); - //bookingEntity2.setBookingPK(new RegistrationBookingPK(DateUtils2.parseDateToLocalDateTime(new Date()))); - bookingEntity2.setBookingDateTime(DateUtils2.parseDateToLocalDateTime(new Date())); - bookingEntity2.setPreregistrationId(bookingPreId); - bookingEntity2.setRegistrationCenterId(oldBooking.getRegistrationCenterId()); - bookingEntity2.setLangCode("eng"); - bookingEntity2.setCrBy("John Doe"); - bookingEntity2.setCrDate(DateUtils2.parseDateToLocalDateTime(new Date())); - bookingEntity2.setRegDate(LocalDate.now().plusDays(30)); - bookingEntity2.setSlotFromTime(LocalTime.of(9, 0)); - bookingEntity2.setSlotToTime(LocalTime.of(9, 15)); - - @SuppressWarnings("rawtypes") - MainResponseDTO mainResponseDTO = new MainResponseDTO<>(); - mainResponseDTO.setErrors(null); - mainResponseDTO.setResponse(bookingEntity2); - Mockito.when(bookingDAO.findByPreRegistrationId("23587986034785")).thenReturn(bookingEntity2); - Mockito.when(bookingDAO.updateAvailibityEntity(availableEntity)).thenReturn(availableEntity); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void successBookAppointmentPendingAppointment() { - - MainRequestDTO bookingRequestDTOs = new MainRequestDTO<>(); - List successBookDtoList = new ArrayList<>(); - BookingRequestDTO successBookDto = new BookingRequestDTO(); - successBookDto.setRegistrationCenterId("1"); - successBookDto.setSlotFromTime(LocalTime.of(9, 0).toString()); - successBookDto.setSlotToTime(LocalTime.of(9, 15).toString()); - successBookDto.setRegDate(LocalDate.now().plusDays(30).toString()); - successBookDtoList.add(successBookDto); - bookingRequestDTOs.setId("mosip.preregistration.booking.book"); - bookingRequestDTOs.setVersion("1.0"); - bookingRequestDTOs.setRequesttime(new Date()); - bookingRequestDTOs.setRequest(successBookDto); - - availableEntity.setAvailableKiosks(3); - availableEntity.setRegcntrId("1"); - availableEntity.setRegDate(LocalDate.now().plusDays(30)); - availableEntity.setToTime(LocalTime.of(9, 0)); - availableEntity.setFromTime(LocalTime.of(9, 15)); - availableEntity.setCrBy("John Doe"); - availableEntity.setCrDate(DateUtils2.parseDateToLocalDateTime(new Date())); - availableEntity.setDeleted(false); - List statusListrebook = new ArrayList<>(); - - PreRegistartionStatusDTO preRegistartionStatus = new PreRegistartionStatusDTO(); - preRegistartionStatus.setStatusCode(StatusCodes.PENDING_APPOINTMENT.getCode()); - preRegistartionStatus.setPreRegistartionId(bookingPreId); - preRegResponse.setResponse(preRegistartionStatus); - statusListrebook.add(preRegistartionStatus); - MainResponseDTO preRegResponseRebook = new MainResponseDTO(); - preRegResponseRebook.setErrors(null); - preRegResponseRebook.setResponse(preRegistartionStatus); - Mockito.when(bookingDAO.findByRegDateAndRegcntrIdAndFromTimeAndToTime(Mockito.any(), Mockito.any(), - Mockito.any(), Mockito.any())).thenReturn(availableEntity); - Mockito.when(bookingDAO.updateAvailibityEntity(availableEntity)).thenReturn(availableEntity); - Mockito.when(serviceUtil.mandatoryParameterCheck(Mockito.anyString(), Mockito.any())).thenReturn(true); - Mockito.when(serviceUtil.validateAppointmentDate(Mockito.any())).thenReturn(true); - Mockito.when(serviceUtil.isKiosksAvailable(Mockito.any())).thenReturn(true); - // Mockito.when(serviceUtil.getDemographicStatus(Mockito.anyString())).thenReturn("Pending_Appointment"); - Mockito.when(serviceUtil.getApplicationBookingStatus(Mockito.anyString())).thenReturn("Pending_Appointment"); - Mockito.when(serviceUtil.getRegCenterMasterData("10001")).thenReturn(centerList); - // Update status - RegistrationBookingEntity bookingEntity2 = new RegistrationBookingEntity(); - //bookingEntity2.setBookingPK(new RegistrationBookingPK(DateUtils2.parseDateToLocalDateTime(new Date()))); - bookingEntity2.setBookingDateTime(DateUtils2.parseDateToLocalDateTime(new Date())); - bookingEntity2.setPreregistrationId(bookingPreId); - bookingEntity2.setRegistrationCenterId(oldBooking.getRegistrationCenterId()); - bookingEntity2.setLangCode("eng"); - bookingEntity2.setCrBy("John Doe"); - bookingEntity2.setCrDate(DateUtils2.parseDateToLocalDateTime(new Date())); - bookingEntity2.setRegDate(LocalDate.now().plusDays(30)); - bookingEntity2.setSlotFromTime(LocalTime.of(9, 0)); - bookingEntity2.setSlotToTime(LocalTime.of(9, 15)); - - MainResponseDTO mainResponseDTO = new MainResponseDTO<>(); - mainResponseDTO.setErrors(null); - mainResponseDTO.setResponse(bookingEntity2); - ResponseEntity> resp2 = new ResponseEntity<>(mainResponseDTO, HttpStatus.OK); - - Mockito.when(bookingDAO.findByPreRegistrationId("23587986034785")).thenReturn(bookingEntity2); - Mockito.when(bookingDAO.updateAvailibityEntity(availableEntity)).thenReturn(availableEntity); - - Mockito.when(restTemplate.exchange(Mockito.anyString(), Mockito.eq(HttpMethod.PUT), Mockito.any(), - Mockito.eq(new ParameterizedTypeReference>() { - }), Mockito.anyMap())).thenReturn(resp2); - - //MainResponseDTO response = service.bookAppointment(bookingRequestDTOs, bookingPreId); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test(expected = RecordNotFoundException.class) - @Ignore - public void bookAppointmentFailureTest() { - - MainRequestDTO bookingRequestDTOs = new MainRequestDTO<>(); - List successBookDtoList = new ArrayList<>(); - BookingRequestDTO successBookDto = new BookingRequestDTO(); - successBookDto.setRegistrationCenterId("1"); - successBookDto.setSlotFromTime(LocalTime.of(9, 0).toString()); - successBookDto.setSlotToTime(LocalTime.of(9, 15).toString()); - successBookDto.setRegDate(LocalDate.now().plusDays(30).toString()); - successBookDtoList.add(successBookDto); - bookingRequestDTOs.setId("mosip.preregistration.booking.book"); - bookingRequestDTOs.setVersion("1.0"); - bookingRequestDTOs.setRequesttime(new Date()); - bookingRequestDTOs.setRequest(successBookDto); - - availableEntity.setAvailableKiosks(3); - availableEntity.setRegcntrId("1"); - availableEntity.setRegDate(LocalDate.now().plusDays(30)); - availableEntity.setToTime(LocalTime.of(9, 0)); - availableEntity.setFromTime(LocalTime.of(9, 15)); - availableEntity.setCrBy("John Doe"); - availableEntity.setCrDate(DateUtils2.parseDateToLocalDateTime(new Date())); - availableEntity.setDeleted(false); - List statusListrebook = new ArrayList<>(); - - PreRegistartionStatusDTO preRegistartionStatus = new PreRegistartionStatusDTO(); - preRegistartionStatus.setStatusCode(StatusCodes.PENDING_APPOINTMENT.getCode()); - preRegistartionStatus.setPreRegistartionId(bookingPreId); - preRegResponse.setResponse(preRegistartionStatus); - statusListrebook.add(preRegistartionStatus); - MainResponseDTO preRegResponseRebook = new MainResponseDTO(); - preRegResponseRebook.setErrors(null); - preRegResponseRebook.setResponse(preRegistartionStatus); - Mockito.when(bookingDAO.findByRegDateAndRegcntrIdAndFromTimeAndToTime(Mockito.any(), Mockito.any(), - Mockito.any(), Mockito.any())).thenReturn(availableEntity); - Mockito.when(serviceUtil.validateAppointmentDate(Mockito.any())).thenReturn(true); - Mockito.when(serviceUtil.mandatoryParameterCheck(Mockito.anyString(), Mockito.any())).thenReturn(true); - - // Update status - RegistrationBookingEntity bookingEntity2 = new RegistrationBookingEntity(); - //bookingEntity2.setBookingPK(new RegistrationBookingPK(DateUtils2.parseDateToLocalDateTime(new Date()))); - bookingEntity2.setBookingDateTime(DateUtils2.parseDateToLocalDateTime(new Date())); - bookingEntity2.setPreregistrationId(bookingPreId); - bookingEntity2.setRegistrationCenterId(oldBooking.getRegistrationCenterId()); - bookingEntity2.setLangCode("eng"); - bookingEntity2.setCrBy("John Doe"); - bookingEntity2.setCrDate(DateUtils2.parseDateToLocalDateTime(new Date())); - bookingEntity2.setRegDate(LocalDate.now().plusDays(30)); - bookingEntity2.setSlotFromTime(LocalTime.of(9, 0)); - bookingEntity2.setSlotToTime(LocalTime.of(9, 15)); - - MainResponseDTO mainResponseDTO = new MainResponseDTO<>(); - mainResponseDTO.setErrors(null); - mainResponseDTO.setResponse(bookingEntity2); - - Mockito.when(bookingDAO.findByPreRegistrationId("23587986034785")).thenReturn(null); - Mockito.when(bookingDAO.updateAvailibityEntity(availableEntity)).thenReturn(availableEntity); - service.bookAppointment(bookingRequestDTOs, bookingPreId); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void successExpiredAppointment() { - - MainRequestDTO bookingRequestDTOs = new MainRequestDTO<>(); - List successBookDtoList = new ArrayList<>(); - BookingRequestDTO successBookDto = new BookingRequestDTO(); - successBookDto.setRegistrationCenterId("1"); - successBookDto.setSlotFromTime(LocalTime.of(9, 0).toString()); - successBookDto.setSlotToTime(LocalTime.of(9, 15).toString()); - successBookDto.setRegDate(LocalDate.now().plusDays(30).toString()); - successBookDtoList.add(successBookDto); - bookingRequestDTOs.setId("mosip.preregistration.booking.book"); - bookingRequestDTOs.setVersion("1.0"); - bookingRequestDTOs.setRequesttime(new Date()); - bookingRequestDTOs.setRequest(successBookDto); - - availableEntity.setAvailableKiosks(3); - availableEntity.setRegcntrId("1"); - availableEntity.setRegDate(LocalDate.now().plusDays(30)); - availableEntity.setToTime(LocalTime.of(9, 0)); - availableEntity.setFromTime(LocalTime.of(9, 15)); - availableEntity.setCrBy("John Doe"); - availableEntity.setCrDate(DateUtils2.parseDateToLocalDateTime(new Date())); - availableEntity.setDeleted(false); - List statusListrebook = new ArrayList<>(); - - PreRegistartionStatusDTO preRegistartionStatus = new PreRegistartionStatusDTO(); - preRegistartionStatus.setStatusCode(StatusCodes.EXPIRED.getCode()); - preRegistartionStatus.setPreRegistartionId(bookingPreId); - preRegResponse.setResponse(preRegistartionStatus); - statusListrebook.add(preRegistartionStatus); - MainResponseDTO preRegResponseRebook = new MainResponseDTO(); - preRegResponseRebook.setErrors(null); - preRegResponseRebook.setResponse(preRegistartionStatus); - Mockito.when(bookingDAO.findByRegDateAndRegcntrIdAndFromTimeAndToTime(Mockito.any(), Mockito.any(), - Mockito.any(), Mockito.any())).thenReturn(availableEntity); - - requestValidatorFlag = validationUtil.requestValidator(bookingRequestDTOs); - - RegistrationCenterDto centerDto = new RegistrationCenterDto(); - List centerList = new ArrayList<>(); - centerDto.setId("10001"); - centerDto.setLangCode("eng"); - centerDto.setCenterStartTime(startTime); - centerDto.setCenterEndTime(endTime); - centerDto.setPerKioskProcessTime(perKioskTime); - centerDto.setLunchStartTime(LunchStartTime); - centerDto.setLunchEndTime(LunchEndTime); - centerDto.setNumberOfKiosks((short) 4); - centerList.add(centerDto); - - // Update status - RegistrationBookingEntity bookingEntity2 = new RegistrationBookingEntity(); - //bookingEntity2.setBookingPK(new RegistrationBookingPK(DateUtils2.parseDateToLocalDateTime(new Date()))); - bookingEntity2.setBookingDateTime(DateUtils2.parseDateToLocalDateTime(new Date())); - bookingEntity2.setPreregistrationId(bookingPreId); - bookingEntity2.setRegistrationCenterId(oldBooking.getRegistrationCenterId()); - bookingEntity2.setLangCode("12L"); - bookingEntity2.setCrBy("John Doe"); - bookingEntity2.setCrDate(DateUtils2.parseDateToLocalDateTime(new Date())); - bookingEntity2.setRegDate(LocalDate.now().plusDays(30)); - bookingEntity2.setSlotFromTime(LocalTime.of(9, 0)); - bookingEntity2.setSlotToTime(LocalTime.of(9, 15)); - - MainResponseDTO mainResponseDTO = new MainResponseDTO<>(); - mainResponseDTO.setErrors(null); - mainResponseDTO.setResponse(bookingEntity2); - - Mockito.when(bookingDAO.findByPreRegistrationId("23587986034785")).thenReturn(bookingEntity2); - Mockito.when(bookingDAO.updateAvailibityEntity(availableEntity)).thenReturn(availableEntity); - Mockito.when(serviceUtil.mandatoryParameterCheck(Mockito.anyString(), Mockito.any())).thenReturn(true); - Mockito.when(serviceUtil.validateAppointmentDate(Mockito.any())).thenReturn(true); - Mockito.when(serviceUtil.isKiosksAvailable(Mockito.any())).thenReturn(true); - Mockito.when(serviceUtil.getApplicationBookingStatus(Mockito.anyString())).thenReturn("Booked"); - Mockito.when(serviceUtil.getRegCenterMasterData("10001")).thenReturn(centerList); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void successMultiBookAppointment() { - - multiBookingListDto.add(multiBookingRequestDto1); - multiBookingListDto.add(multiBookingRequestDto2); - - MultiBookingRequest multiBookingRequest = new MultiBookingRequest(); - multiBookingRequest.setBookingRequest(multiBookingListDto); - responseDto.setResponsetime(serviceUtil.getCurrentResponseTime()); - - BookingStatusDTO bookingStatusDTO1 = new BookingStatusDTO(); - bookingStatusDTO1.setBookingMessage("Appointment booked successfully"); - - BookingStatusDTO bookingStatusDTO2 = new BookingStatusDTO(); - bookingStatusDTO2.setBookingMessage("Appointment booked successfully"); - - List bookingStatusDTOs = new ArrayList<>(); - bookingStatusDTOs.add(bookingStatusDTO1); - bookingStatusDTOs.add(bookingStatusDTO2); - - MainRequestDTO bookingRequestDTOs = new MainRequestDTO<>(); - MultiBookingRequest bookingRequest = new MultiBookingRequest(); - List successBookDtoList = new ArrayList<>(); - MultiBookingRequestDTO successBookDto1 = new MultiBookingRequestDTO(); - successBookDto1.setPreRegistrationId("23587986034785"); - successBookDto1.setRegistrationCenterId("1"); - successBookDto1.setSlotFromTime(LocalTime.of(9, 0).toString()); - successBookDto1.setSlotToTime(LocalTime.of(9, 15).toString()); - successBookDto1.setRegDate(LocalDate.now().plusDays(30).toString()); - successBookDtoList.add(successBookDto1); - bookingRequest.setBookingRequest(successBookDtoList); - bookingRequestDTOs.setRequest(bookingRequest); - bookingRequestDTOs.setId("mosip.preregistration.booking.book"); - bookingRequestDTOs.setVersion("1.0"); - bookingRequestDTOs.setRequesttime(new Date()); - - availableEntity.setAvailableKiosks(3); - availableEntity.setRegcntrId("1"); - availableEntity.setRegDate(LocalDate.now().plusDays(30)); - availableEntity.setToTime(LocalTime.of(9, 0)); - availableEntity.setFromTime(LocalTime.of(9, 15)); - availableEntity.setCrBy("John Doe"); - availableEntity.setCrDate(DateUtils2.parseDateToLocalDateTime(new Date())); - availableEntity.setDeleted(false); - List statusListrebook = new ArrayList<>(); - - PreRegistartionStatusDTO preRegistartionStatus = new PreRegistartionStatusDTO(); - preRegistartionStatus.setStatusCode(StatusCodes.BOOKED.getCode()); - preRegistartionStatus.setPreRegistartionId(bookingPreId); - preRegResponse.setResponse(preRegistartionStatus); - statusListrebook.add(preRegistartionStatus); - MainResponseDTO preRegResponseRebook = new MainResponseDTO(); - preRegResponseRebook.setErrors(null); - preRegResponseRebook.setResponse(preRegistartionStatus); - Mockito.when(bookingDAO.findByRegDateAndRegcntrIdAndFromTimeAndToTime(Mockito.any(), Mockito.any(), - Mockito.any(), Mockito.any())).thenReturn(availableEntity); - - requestValidatorFlag = validationUtil.requestValidator(bookingRequestDTOs); - - // Update status - RegistrationBookingEntity bookingEntity2 = new RegistrationBookingEntity(); - //bookingEntity2.setBookingPK(new RegistrationBookingPK(DateUtils2.parseDateToLocalDateTime(new Date()))); - bookingEntity2.setBookingDateTime(DateUtils2.parseDateToLocalDateTime(new Date())); - bookingEntity2.setPreregistrationId(bookingPreId); - bookingEntity2.setRegistrationCenterId(oldBooking.getRegistrationCenterId()); - bookingEntity2.setLangCode("12L"); - bookingEntity2.setCrBy("John Doe"); - bookingEntity2.setCrDate(DateUtils2.parseDateToLocalDateTime(new Date())); - bookingEntity2.setRegDate(LocalDate.now().plusDays(30)); - bookingEntity2.setSlotFromTime(LocalTime.of(9, 0)); - bookingEntity2.setSlotToTime(LocalTime.of(9, 15)); - - RegistrationCenterDto centerDto = new RegistrationCenterDto(); - List centerList = new ArrayList<>(); - centerDto.setId("10001"); - centerDto.setLangCode("eng"); - centerDto.setCenterStartTime(startTime); - centerDto.setCenterEndTime(endTime); - centerDto.setPerKioskProcessTime(perKioskTime); - centerDto.setLunchStartTime(LunchStartTime); - centerDto.setLunchEndTime(LunchEndTime); - centerDto.setNumberOfKiosks((short) 4); - centerList.add(centerDto); - - Mockito.when(bookingDAO.findByPreRegistrationId("23587986034785")).thenReturn(bookingEntity2); - Mockito.when(bookingDAO.updateAvailibityEntity(availableEntity)).thenReturn(availableEntity); - Mockito.when(serviceUtil.mandatoryParameterCheck(Mockito.anyString(), Mockito.any())).thenReturn(true); - Mockito.when(serviceUtil.validateAppointmentDate(Mockito.any())).thenReturn(true); - Mockito.when(serviceUtil.isKiosksAvailable(Mockito.any())).thenReturn(true); - Mockito.when(serviceUtil.getApplicationBookingStatus(Mockito.anyString())).thenReturn("Booked"); - Mockito.when(serviceUtil.getRegCenterMasterData("10001")).thenReturn(centerList); - - MainResponseDTO mainResponseDTO = new MainResponseDTO<>(); - mainResponseDTO.setErrors(null); - mainResponseDTO.setResponse(bookingEntity2); - Mockito.when(bookingDAO.findByPreRegistrationId("23587986034785")).thenReturn(bookingEntity2); - Mockito.when(bookingDAO.updateAvailibityEntity(availableEntity)).thenReturn(availableEntity); - -// MainResponseDTO response = service.bookMultiAppointment(bookingRequestDTOs); -// assertNotNull(response.getResponse().getBookingStatusResponse().get(0).getBookingMessage()); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void successExpiredMultiBookAppointment() { - multiBookingListDto.add(multiBookingRequestDto1); - multiBookingListDto.add(multiBookingRequestDto2); - - MultiBookingRequest multiBookingRequest = new MultiBookingRequest(); - multiBookingRequest.setBookingRequest(multiBookingListDto); - responseDto.setResponsetime(serviceUtil.getCurrentResponseTime()); - - BookingStatusDTO bookingStatusDTO1 = new BookingStatusDTO(); - bookingStatusDTO1.setBookingMessage("Appointment booked successfully"); - - BookingStatusDTO bookingStatusDTO2 = new BookingStatusDTO(); - bookingStatusDTO2.setBookingMessage("Appointment booked successfully"); - RegistrationCenterDto centerDto = new RegistrationCenterDto(); - List centerList = new ArrayList<>(); - centerDto.setId("10001"); - centerDto.setLangCode("eng"); - centerDto.setCenterStartTime(startTime); - centerDto.setCenterEndTime(endTime); - centerDto.setPerKioskProcessTime(perKioskTime); - centerDto.setLunchStartTime(LunchStartTime); - centerDto.setLunchEndTime(LunchEndTime); - centerDto.setNumberOfKiosks((short) 4); - centerList.add(centerDto); - - List bookingStatusDTOs = new ArrayList<>(); - bookingStatusDTOs.add(bookingStatusDTO1); - bookingStatusDTOs.add(bookingStatusDTO2); - - MainRequestDTO bookingRequestDTOs = new MainRequestDTO<>(); - MultiBookingRequest bookingRequest = new MultiBookingRequest(); - List successBookDtoList = new ArrayList<>(); - MultiBookingRequestDTO successBookDto1 = new MultiBookingRequestDTO(); - successBookDto1.setPreRegistrationId("23587986034785"); - successBookDto1.setRegistrationCenterId("1"); - successBookDto1.setSlotFromTime(LocalTime.of(9, 0).toString()); - successBookDto1.setSlotToTime(LocalTime.of(9, 15).toString()); - successBookDto1.setRegDate(LocalDate.now().plusDays(30).toString()); - successBookDtoList.add(successBookDto1); - bookingRequest.setBookingRequest(successBookDtoList); - bookingRequestDTOs.setRequest(bookingRequest); - bookingRequestDTOs.setId("mosip.preregistration.booking.book"); - bookingRequestDTOs.setVersion("1.0"); - bookingRequestDTOs.setRequesttime(new Date()); - - availableEntity.setAvailableKiosks(3); - availableEntity.setRegcntrId("1"); - availableEntity.setRegDate(LocalDate.now().plusDays(30)); - availableEntity.setToTime(LocalTime.of(9, 0)); - availableEntity.setFromTime(LocalTime.of(9, 15)); - availableEntity.setCrBy("John Doe"); - availableEntity.setCrDate(DateUtils2.parseDateToLocalDateTime(new Date())); - availableEntity.setDeleted(false); - List statusListrebook = new ArrayList<>(); - - PreRegistartionStatusDTO preRegistartionStatus = new PreRegistartionStatusDTO(); - preRegistartionStatus.setStatusCode(StatusCodes.EXPIRED.getCode()); - preRegistartionStatus.setPreRegistartionId(bookingPreId); - preRegResponse.setResponse(preRegistartionStatus); - statusListrebook.add(preRegistartionStatus); - MainResponseDTO preRegResponseRebook = new MainResponseDTO(); - preRegResponseRebook.setErrors(null); - preRegResponseRebook.setResponse(preRegistartionStatus); - Mockito.when(bookingDAO.findByRegDateAndRegcntrIdAndFromTimeAndToTime(Mockito.any(), Mockito.any(), - Mockito.any(), Mockito.any())).thenReturn(availableEntity); - - MainResponseDTO statusResponse = new MainResponseDTO(); - statusResponse.setResponse("Booked"); - - requestValidatorFlag = validationUtil.requestValidator(bookingRequestDTOs); - Mockito.when(serviceUtil.getApplicationStatus("23587986034785")).thenReturn(statusResponse); - - // Update status - RegistrationBookingEntity bookingEntity2 = new RegistrationBookingEntity(); - //bookingEntity2.setBookingPK(new RegistrationBookingPK(DateUtils2.parseDateToLocalDateTime(new Date()))); - bookingEntity2.setBookingDateTime(DateUtils2.parseDateToLocalDateTime(new Date())); - bookingEntity2.setPreregistrationId(bookingPreId); - bookingEntity2.setRegistrationCenterId(oldBooking.getRegistrationCenterId()); - bookingEntity2.setLangCode("12L"); - bookingEntity2.setCrBy("987654321"); - bookingEntity2.setCrDate(DateUtils2.parseDateToLocalDateTime(new Date())); - bookingEntity2.setRegDate(LocalDate.now().plusDays(30)); - bookingEntity2.setSlotFromTime(LocalTime.of(9, 0)); - bookingEntity2.setSlotToTime(LocalTime.of(9, 15)); - - MainResponseDTO mainResponseDTO = new MainResponseDTO<>(); - mainResponseDTO.setErrors(null); - mainResponseDTO.setResponse(bookingEntity2); - Mockito.when(serviceUtil.getApplicationBookingStatus("23587986034785")).thenReturn("Pending_Appointment"); - BookingRequestDTO bookingreq = new BookingRequestDTO(); - bookingreq.setRegDate(LocalDate.now().plusDays(30).toString()); - Mockito.when(serviceUtil.mandatoryParameterCheck(Mockito.anyString(), Mockito.any())).thenReturn(true); - Mockito.when(serviceUtil.validateAppointmentDate(Mockito.any())).thenReturn(true); - Mockito.when(bookingDAO.findByPreRegistrationId("23587986034785")).thenReturn(bookingEntity2); - Mockito.when(serviceUtil.isKiosksAvailable(Mockito.any())).thenReturn(true); - Mockito.when(bookingDAO.updateAvailibityEntity(availableEntity)).thenReturn(availableEntity); - Mockito.when(serviceUtil.getRegCenterMasterData("10001")).thenReturn(centerList); -// MainResponseDTO response = service.bookMultiAppointment(bookingRequestDTOs); -// assertNotNull(response.getResponse().getBookingStatusResponse().get(0).getBookingMessage()); - } - - /* - * @SuppressWarnings("unchecked") - * - * @Test public void failureMultiBookAppointment() { - * multiBookingListDto.add(multiBookingRequestDto1); - * multiBookingListDto.add(multiBookingRequestDto2); - * - * MultiBookingRequest multiBookingRequest = new MultiBookingRequest(); - * multiBookingRequest.setBookingRequest(multiBookingListDto); - * responseDto.setResponsetime(serviceUtil.getCurrentResponseTime()); - * - * BookingStatusDTO bookingStatusDTO1 = new BookingStatusDTO(); - * bookingStatusDTO1.setBookingMessage("Appointment booked successfully"); - * - * BookingStatusDTO bookingStatusDTO2 = new BookingStatusDTO(); - * bookingStatusDTO2.setBookingMessage("Appointment booked successfully"); - * - * List bookingStatusDTOs = new ArrayList<>(); - * bookingStatusDTOs.add(bookingStatusDTO1); - * bookingStatusDTOs.add(bookingStatusDTO2); - * - * MainRequestDTO bookingRequestDTOs = new - * MainRequestDTO<>(); MultiBookingRequest bookingRequest = new - * MultiBookingRequest(); List successBookDtoList = new - * ArrayList<>(); MultiBookingRequestDTO successBookDto1 = new - * MultiBookingRequestDTO(); - * successBookDto1.setPreRegistrationId("23587986034785"); - * successBookDto1.setRegistrationCenterId("1"); - * successBookDto1.setSlotFromTime(LocalTime.of(9, 0).toString()); - * successBookDto1.setSlotToTime(LocalTime.of(9, 15).toString()); - * successBookDto1.setRegDate(LocalDate.now().plusDays(30).toString()); - * successBookDtoList.add(successBookDto1); - * bookingRequest.setBookingRequest(successBookDtoList); - * bookingRequestDTOs.setRequest(bookingRequest); - * bookingRequestDTOs.setId("mosip.preregistration.booking.book"); - * bookingRequestDTOs.setVersion("1.0"); bookingRequestDTOs.setRequesttime(new - * Date()); - * - * availableEntity.setAvailableKiosks(3); availableEntity.setRegcntrId("1"); - * availableEntity.setRegDate(LocalDate.now().plusDays(30)); - * availableEntity.setToTime(LocalTime.of(9, 0)); - * availableEntity.setFromTime(LocalTime.of(9, 15)); - * availableEntity.setCrBy("JOhn Doe"); - * availableEntity.setCrDate(DateUtils2.parseDateToLocalDateTime(new Date())); - * availableEntity.setDeleted(false); List - * statusListrebook = new ArrayList<>(); - * - * PreRegistartionStatusDTO preRegistartionStatus = new - * PreRegistartionStatusDTO(); - * preRegistartionStatus.setStatusCode(StatusCodes.BOOKED.getCode()); - * preRegistartionStatus.setPreRegistartionId(bookingPreId); - * preRegResponse.setResponse(preRegistartionStatus); - * statusListrebook.add(preRegistartionStatus); - * MainResponseDTO preRegResponseRebook = new - * MainResponseDTO(); - * preRegResponseRebook.setErrors(null); - * preRegResponseRebook.setResponse(preRegistartionStatus); - * Mockito.when(bookingDAO.findByRegDateAndRegcntrIdAndFromTimeAndToTime(Mockito - * .any(), Mockito.any(), Mockito.any(), - * Mockito.any())).thenReturn(availableEntity); - * - * requestValidatorFlag = validationUtil.requestValidator(bookingRequestDTOs); - * ResponseEntity> respEntity = new - * ResponseEntity<>(preRegResponse, HttpStatus.OK); - * Mockito.when(restTemplate.exchange(Mockito.anyString(), - * Mockito.eq(HttpMethod.GET), Mockito.any(), - * - * Mockito.eq(new - * ParameterizedTypeReference>() { }), - * Mockito.anyMap())).thenReturn(respEntity); - * - * // Update status RegistrationBookingEntity bookingEntity2 = new - * RegistrationBookingEntity(); bookingEntity2.setBookingPK(new - * RegistrationBookingPK(DateUtils2.parseDateToLocalDateTime(new Date()))); - * bookingEntity2.setRegistrationCenterId(oldBooking.getRegistrationCenterId()); - * bookingEntity2.setLangCode("12L"); bookingEntity2.setCrBy("987654321"); - * bookingEntity2.setCrDate(DateUtils2.parseDateToLocalDateTime(new Date())); - * bookingEntity2.setRegDate(LocalDate.now().plusDays(30)); - * bookingEntity2.setSlotFromTime(LocalTime.of(9, 0)); - * bookingEntity2.setSlotToTime(LocalTime.of(9, 15)); - * - * MainResponseDTO mainResponseDTO = new MainResponseDTO<>(); - * mainResponseDTO.setErrors(null); mainResponseDTO.setResponse(bookingEntity2); - * ResponseEntity> resp2 = new - * ResponseEntity<>(mainResponseDTO, HttpStatus.OK); - * - * Mockito.when(bookingDAO.findByPreRegistrationId("23587986034785")).thenReturn - * (null); - * Mockito.when(bookingDAO.updateAvailibityEntity(availableEntity)).thenReturn( - * availableEntity); - * - * Mockito.when(restTemplate.exchange(Mockito.anyString(), - * Mockito.eq(HttpMethod.PUT), Mockito.any(), Mockito.eq(new - * ParameterizedTypeReference>() { }), - * Mockito.anyMap())).thenReturn(resp2); - * - * MainResponseDTO response = - * service.bookMultiAppointment(bookingRequestDTOs); - * assertEquals("Appointment booked successfully", - * response.getResponse().getBookingStatusResponse().get(0).getBookingMessage()) - * ; } - */ - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Test - public void cancelAppointmentSuccessTest() throws java.text.ParseException { - - PreRegistartionStatusDTO bookedStatusDTO = new PreRegistartionStatusDTO(); - bookedStatusDTO.setStatusCode(StatusCodes.BOOKED.getCode()); - bookedStatusDTO.setPreRegistartionId("23587986034785"); - preRegResponse.setResponse(bookedStatusDTO); - - requestValidatorFlag = validationUtil.requestValidator(cancelRequestdto); - - MainResponseDTO getApplicationStatus = new MainResponseDTO<>(); - PreRegistartionStatusDTO preRegistartionStatus = new PreRegistartionStatusDTO(); - preRegistartionStatus.setStatusCode(StatusCodes.BOOKED.getCode()); - preRegistartionStatus.setPreRegistartionId("12345678909876"); - getApplicationStatus.setResponse(preRegistartionStatus); - MainResponseDTO statusResponse = new MainResponseDTO(); - statusResponse.setResponse(StatusCodes.BOOKED.getCode()); - Mockito.when(serviceUtil.getApplicationStatus(Mockito.anyString())).thenReturn(statusResponse); - Mockito.when(bookingDAO.findByRegDateAndRegcntrIdAndFromTimeAndToTime(Mockito.any(), Mockito.any(), - Mockito.any(), Mockito.any())).thenReturn(availableEntity); - - Mockito.when(bookingDAO.findByPreRegistrationId(Mockito.any())).thenReturn(bookingEntity); - - Mockito.when(bookingDAO.deleteByPreRegistrationId(Mockito.anyString())).thenReturn(1); - MainResponseDTO mainResponseDTO = new MainResponseDTO<>(); - mainResponseDTO.setErrors(null); - mainResponseDTO.setResponse(bookingEntity); - BookingRequestDTO bookingRequestDTO = new BookingRequestDTO(); - bookingRequestDTO.setRegistrationCenterId("1"); - bookingRequestDTO.setSlotFromTime(LocalTime.of(9, 0).toString()); - bookingRequestDTO.setSlotToTime(LocalTime.of(9, 15).toString()); - bookingRequestDTO.setRegDate(LocalDate.now().plusDays(30).toString()); - Mockito.when(serviceUtil.mandatoryParameterCheckforCancel("23587986034785")).thenReturn(true); - Mockito.when(serviceUtil.getDemographicStatusForCancel("23587986034785")).thenReturn(true); - availableEntity.setAvailableKiosks(availableEntity.getAvailableKiosks() + 1); - Mockito.when(bookingDAO.updateAvailibityEntity(availableEntity)).thenReturn(availableEntity); -// MainResponseDTO responseDto = service.cancelAppointment("23587986034785"); -// assertNotNull(responseDto.getResponse()); - } - - @Test - public void getAppointmentDetailsTest() { - MainRequestDTO reBookingMainDto = new MainRequestDTO<>(); - BookingRequestDTO bookingRequestDTO = new BookingRequestDTO(); - bookingRequestDTO.setRegistrationCenterId("1"); - bookingRequestDTO.setSlotFromTime(LocalTime.of(9, 0).toString()); - bookingRequestDTO.setSlotToTime(LocalTime.of(9, 15).toString()); - bookingRequestDTO.setRegDate(LocalDate.now().plusDays(30).toString()); - - List rebookingReqList = new ArrayList<>(); - rebookingReqList.add(bookingRequestDTO); - - reBookingMainDto.setId("mosip.pre-registration.booking.book"); - reBookingMainDto.setVersion("1.0"); - reBookingMainDto.setRequesttime(new Date()); - reBookingMainDto.setRequest(bookingRequestDTO); - - MainResponseDTO> responseDTO = new MainResponseDTO<>(); - BookingStatusDTO bookingStatusDTO = new BookingStatusDTO(); - bookingStatusDTO.setBookingMessage("Appointment booked successfully"); - - List respList = new ArrayList<>(); - respList.add(bookingStatusDTO); - responseDTO.setResponse(respList); - responseDTO.setResponsetime(serviceUtil.getCurrentResponseTime()); - List statusListrebook = new ArrayList<>(); - PreRegistartionStatusDTO preRegistartionStatus = new PreRegistartionStatusDTO(); - preRegistartionStatus.setStatusCode(StatusCodes.BOOKED.getCode()); - preRegistartionStatus.setPreRegistartionId("12345678909876"); - statusListrebook.add(preRegistartionStatus); - MainResponseDTO preRegResponseRebook = new MainResponseDTO(); - preRegResponseRebook.setErrors(null); - preRegResponseRebook.setResponse(preRegistartionStatus); - RegistrationBookingEntity bookingEntityRebook = new RegistrationBookingEntity(); - //bookingEntityRebook.setBookingPK(new RegistrationBookingPK(DateUtils2.parseDateToLocalDateTime(new Date()))); - bookingEntityRebook.setBookingDateTime(DateUtils2.parseDateToLocalDateTime(new Date())); - bookingEntityRebook.setPreregistrationId(bookingPreId); - bookingEntityRebook.setRegistrationCenterId(oldBooking.getRegistrationCenterId()); - bookingEntityRebook.setLangCode("eng"); - bookingEntityRebook.setCrBy("John Doe"); - bookingEntityRebook.setCrDate(DateUtils2.parseDateToLocalDateTime(new Date())); - bookingEntityRebook.setRegDate(LocalDate.now().plusDays(30)); - bookingEntityRebook.setSlotFromTime(LocalTime.of(9, 0)); - bookingEntityRebook.setSlotToTime(LocalTime.of(9, 15)); - Mockito.when(bookingDAO.findByPreRegistrationId("12345678909876")).thenReturn(bookingEntityRebook); - ResponseEntity> respEntity = new ResponseEntity<>( - preRegResponseRebook, HttpStatus.OK); - Mockito.when(restTemplate.exchange(Mockito.anyString(), Mockito.eq(HttpMethod.GET), Mockito.any(), - - Mockito.eq(new ParameterizedTypeReference>() { - }), Mockito.anyMap())).thenReturn(respEntity); - - MainResponseDTO responseDto = service.getAppointmentDetails("12345678909876"); - - assertEquals("1", responseDto.getResponse().getRegistrationCenterId()); - } - - @SuppressWarnings("unchecked") - @Test(expected = BookingDataNotFoundException.class) - public void getAppointmentDetailsTestFail() { - - PreRegistartionStatusDTO bookedStatusDTO = new PreRegistartionStatusDTO(); - bookedStatusDTO.setStatusCode(StatusCodes.BOOKED.getCode()); - bookedStatusDTO.setPreRegistartionId("23587986034785"); - preRegResponse.setResponse(bookedStatusDTO); - - BookingDataNotFoundException exception = new BookingDataNotFoundException( - ErrorCodes.PRG_BOOK_RCI_013.toString(), ErrorMessages.BOOKING_DATA_NOT_FOUND.toString()); - Mockito.when(bookingDAO.findByPreRegistrationId("23587986034785")).thenThrow(exception); - ResponseEntity> respEntity = new ResponseEntity<>(preRegResponse, - HttpStatus.OK); - Mockito.when(restTemplate.exchange(Mockito.anyString(), Mockito.eq(HttpMethod.GET), Mockito.any(), - - Mockito.eq(new ParameterizedTypeReference>() { - }), Mockito.anyMap())).thenReturn(respEntity); - - service.getAppointmentDetails("23587986034785"); - - } - - @SuppressWarnings("unchecked") - @Test(expected = TableNotAccessibleException.class) - public void getAppointmentDetailsFailureTest() { - PreRegistartionStatusDTO bookedStatusDTO = new PreRegistartionStatusDTO(); - bookedStatusDTO.setStatusCode(StatusCodes.BOOKED.getCode()); - bookedStatusDTO.setPreRegistartionId("23587986034785"); - preRegResponse.setResponse(bookedStatusDTO); - - ResponseEntity> respEntity = new ResponseEntity<>(preRegResponse, - HttpStatus.OK); - Mockito.when(restTemplate.exchange(Mockito.anyString(), Mockito.eq(HttpMethod.GET), Mockito.any(), - - Mockito.eq(new ParameterizedTypeReference>() { - }), Mockito.anyMap())).thenReturn(respEntity); - - Mockito.when(bookingDAO.findByPreRegistrationId(Mockito.anyString())) - .thenThrow(new DataAccessLayerException("", "", new Throwable())); - service.getAppointmentDetails("23587986034785"); - } - - @Test - public void cancelAppointmentBatch() { - - MainRequestDTO bookingRequestDTOs = new MainRequestDTO<>(); - List successBookDtoList = new ArrayList<>(); - BookingRequestDTO successBookDto = new BookingRequestDTO(); - successBookDto.setRegistrationCenterId("1"); - successBookDto.setSlotFromTime(LocalTime.of(9, 0).toString()); - successBookDto.setSlotToTime(LocalTime.of(9, 15).toString()); - successBookDto.setRegDate(LocalDate.now().plusDays(30).toString()); - successBookDtoList.add(successBookDto); - bookingRequestDTOs.setId("mosip.pre-registration.booking.book"); - bookingRequestDTOs.setVersion("1.0"); - bookingRequestDTOs.setRequesttime(new Date()); - bookingRequestDTOs.setRequest(successBookDto); - RegistrationCenterDto centerDto = new RegistrationCenterDto(); - List centerList = new ArrayList<>(); - centerDto.setId("10001"); - centerDto.setLangCode("eng"); - centerDto.setCenterStartTime(startTime); - centerDto.setCenterEndTime(endTime); - centerDto.setPerKioskProcessTime(perKioskTime); - centerDto.setLunchStartTime(LunchStartTime); - centerDto.setLunchEndTime(LunchEndTime); - centerDto.setNumberOfKiosks((short) 4); - centerList.add(centerDto); - RegistrationBookingEntity bookingEntity = new RegistrationBookingEntity(); - //bookingEntity.setBookingPK(new RegistrationBookingPK(DateUtils2.parseDateToLocalDateTime(new Date()))); - bookingEntity.setBookingDateTime(DateUtils2.parseDateToLocalDateTime(new Date())); - bookingEntity.setPreregistrationId(bookingPreId); - bookingEntity.setRegistrationCenterId(oldBooking.getRegistrationCenterId()); - bookingEntity.setLangCode("eng"); - bookingEntity.setCrBy("John Doe"); - bookingEntity.setCrDate(DateUtils2.parseDateToLocalDateTime(new Date())); - Mockito.when(bookingDAO.findByPreRegistrationId("23587986034785")).thenReturn(bookingEntity); - Mockito.when(bookingDAO.updateAvailibityEntity(availableEntity)).thenReturn(availableEntity); - Mockito.when(serviceUtil.mandatoryParameterCheck(Mockito.anyString(), Mockito.any())).thenReturn(true); - Mockito.when(serviceUtil.validateAppointmentDate(Mockito.any())).thenReturn(true); - Mockito.when(serviceUtil.isKiosksAvailable(Mockito.any())).thenReturn(true); - Mockito.when(serviceUtil.mandatoryParameterCheckforCancel(Mockito.anyString())).thenReturn(true); - Mockito.when(serviceUtil.getDemographicStatusForCancel(Mockito.anyString())).thenReturn(true); - Mockito.when(serviceUtil.getApplicationBookingStatus("23587986034785")).thenReturn("Expired"); - Mockito.when(serviceUtil.getRegCenterMasterData("10001")).thenReturn(centerList); - Mockito.when(bookingDAO.findByRegDateAndRegcntrIdAndFromTimeAndToTime(Mockito.any(), Mockito.any(), - Mockito.any(), Mockito.any())).thenReturn(availableEntity); - Mockito.when(bookingDAO.updateAvailibityEntity(availableEntity)).thenReturn(availableEntity); - Mockito.when(bookingDAO.saveRegistrationEntityForBooking(Mockito.any())).thenReturn(bookingEntity); - - MainResponseDTO response = service.cancelAppointmentBatch("23587986034785"); - } - - @SuppressWarnings("unchecked") - @Test(expected = TimeSpanException.class) - public void cancelTimeSpanFailureTest() throws java.text.ParseException { - - TimeSpanException ex = new TimeSpanException(ErrorCodes.PRG_BOOK_RCI_026.getCode(), - ErrorMessages.CANCEL_BOOKING_CANNOT_BE_DONE.getMessage() + " " + 24 + "hours"); - - List registrationEntityList = new ArrayList<>(); - RegistrationBookingEntity bookingEntity = new RegistrationBookingEntity(); - //bookingEntity.setBookingPK(new RegistrationBookingPK(DateUtils2.parseDateToLocalDateTime(new Date()))); - bookingEntity.setBookingDateTime(DateUtils2.parseDateToLocalDateTime(new Date())); - bookingEntity.setPreregistrationId(bookingPreId); - bookingEntity.setRegistrationCenterId(oldBooking.getRegistrationCenterId()); - bookingEntity.setLangCode("eng"); - bookingEntity.setCrBy("John Doe"); - bookingEntity.setCrDate(DateUtils2.parseDateToLocalDateTime(new Date())); - bookingEntity.setRegDate(LocalDate.now()); - bookingEntity.setSlotFromTime(LocalTime.parse(oldBooking.getSlotFromTime())); - bookingEntity.setSlotToTime(LocalTime.parse(oldBooking.getSlotToTime())); - registrationEntityList.add(bookingEntity); - MainRequestDTO cancelRequestdto2 = new MainRequestDTO<>(); - cancelRequestdto2.setRequesttime(new Date()); - cancelRequestdto2.setRequest(cancelbookingDto); - cancelRequestdto2.setId("mosip.pre-registration.booking.book"); - cancelRequestdto2.setVersion("1.0"); - CancelBookingDTO cancelbookingDto2 = new CancelBookingDTO(); - cancelbookingDto2.setRegDate(LocalDate.now().toString()); - cancelbookingDto2.setRegistrationCenterId("1"); - cancelbookingDto2.setSlotFromTime(LocalTime.now().toString()); - cancelbookingDto2.setSlotToTime(LocalTime.of(9, 13).toString()); - - PreRegistartionStatusDTO bookedStatusDTO = new PreRegistartionStatusDTO(); - bookedStatusDTO.setStatusCode(StatusCodes.BOOKED.getCode()); - bookedStatusDTO.setPreRegistartionId("23587986034785"); - preRegResponse.setResponse(bookedStatusDTO); - - requestValidatorFlag = validationUtil.requestValidator(cancelRequestdto); - RegistrationCenterDto centerDto = new RegistrationCenterDto(); - List centerList = new ArrayList<>(); - centerDto.setId("10001"); - centerDto.setLangCode("eng"); - centerDto.setCenterStartTime(startTime); - centerDto.setCenterEndTime(endTime); - centerDto.setPerKioskProcessTime(perKioskTime); - centerDto.setLunchStartTime(LunchStartTime); - centerDto.setLunchEndTime(LunchEndTime); - centerDto.setNumberOfKiosks((short) 4); - centerList.add(centerDto); - Mockito.when(bookingDAO.updateAvailibityEntity(availableEntity)).thenReturn(availableEntity); - Mockito.when(serviceUtil.mandatoryParameterCheck(Mockito.anyString(), Mockito.any())).thenReturn(true); - Mockito.when(serviceUtil.mandatoryParameterCheckforCancel(Mockito.any())).thenReturn(true); - Mockito.when(serviceUtil.getDemographicStatusForCancel(Mockito.any())).thenReturn(true); - Mockito.when(serviceUtil.validateAppointmentDate(Mockito.any())).thenReturn(true); - Mockito.when(serviceUtil.isKiosksAvailable(Mockito.any())).thenReturn(true); - Mockito.when(serviceUtil.getApplicationBookingStatus("23587986034785")).thenReturn("Booked"); - Mockito.when(serviceUtil.getRegCenterMasterData("10001")).thenReturn(centerList); - Mockito.when(serviceUtil.timeSpanCheckForCancle(Mockito.any())).thenThrow(ex); - - Mockito.when(bookingDAO.findByPreRegistrationId("23587986034785")).thenReturn(bookingEntity); - - Mockito.when(bookingDAO.findByRegDateAndRegcntrIdAndFromTimeAndToTime(Mockito.any(), Mockito.any(), - Mockito.any(), Mockito.any())).thenReturn(availableEntity); - service.cancelBooking("23587986034785", false); - } - - @Test - public void deleteBooking() { - - List deleteList = new ArrayList<>(); - DeleteBookingDTO deleteDto = new DeleteBookingDTO(); - List registrationEntityList = new ArrayList<>(); - RegistrationBookingEntity bookingEntity = new RegistrationBookingEntity(); - //bookingEntity.setBookingPK(new RegistrationBookingPK(DateUtils2.parseDateToLocalDateTime(new Date()))); - bookingEntity.setBookingDateTime(DateUtils2.parseDateToLocalDateTime(new Date())); - bookingEntity.setPreregistrationId(bookingPreId); - bookingEntity.setRegistrationCenterId(oldBooking.getRegistrationCenterId()); - bookingEntity.setLangCode("eng"); - bookingEntity.setCrBy("John Doe"); - bookingEntity.setCrDate(DateUtils2.parseDateToLocalDateTime(new Date())); - bookingEntity.setRegDate(LocalDate.parse(oldBooking.getRegDate())); - bookingEntity.setSlotFromTime(LocalTime.parse(oldBooking.getSlotFromTime())); - bookingEntity.setSlotToTime(LocalTime.parse(oldBooking.getSlotToTime())); - registrationEntityList.add(bookingEntity); - - Mockito.when(bookingDAO.findByPreRegistrationId(Mockito.anyString())).thenReturn(bookingEntity); - deleteDto.setDeletedBy("John Doe"); - deleteDto.setDeletedDateTime(new Date(System.currentTimeMillis())); - deleteDto.setPreRegistrationId("23587986034785"); - deleteList.add(deleteDto); - Mockito.when(bookingDAO.deleteByPreRegistrationId(Mockito.anyString())).thenReturn(1); - - MainResponseDTO response = new MainResponseDTO<>(); - response.setErrors(null); - response.setResponse(deleteDto); - response.setResponsetime(serviceUtil.getCurrentResponseTime()); - Mockito.when(bookingDAO.findByRegDateAndRegcntrIdAndFromTimeAndToTime(Mockito.any(), Mockito.anyString(), - Mockito.any(), Mockito.any())).thenReturn(availableEntity); - Mockito.when(bookingDAO.updateAvailibityEntity(availableEntity)).thenReturn(availableEntity); - - } - - @Test - public void deleteBookingFailTest() { - - List deleteList = new ArrayList<>(); - DeleteBookingDTO deleteDto = new DeleteBookingDTO(); - List registrationEntityList = new ArrayList<>(); - RegistrationBookingEntity bookingEntity = new RegistrationBookingEntity(); - //bookingEntity.setBookingPK(new RegistrationBookingPK(DateUtils2.parseDateToLocalDateTime(new Date()))); - bookingEntity.setBookingDateTime(DateUtils2.parseDateToLocalDateTime(new Date())); - bookingEntity.setPreregistrationId(bookingPreId); - bookingEntity.setRegistrationCenterId(oldBooking.getRegistrationCenterId()); - bookingEntity.setLangCode("eng"); - bookingEntity.setCrBy("John Doe"); - bookingEntity.setCrDate(DateUtils2.parseDateToLocalDateTime(new Date())); - bookingEntity.setRegDate(LocalDate.parse(oldBooking.getRegDate())); - bookingEntity.setSlotFromTime(LocalTime.parse(oldBooking.getSlotFromTime())); - bookingEntity.setSlotToTime(LocalTime.parse(oldBooking.getSlotToTime())); - registrationEntityList.add(bookingEntity); - - Mockito.when(bookingDAO.findByPreregistrationId(Mockito.anyString())).thenReturn(null); - deleteDto.setDeletedBy("John Doe"); - deleteDto.setDeletedDateTime(new Date(System.currentTimeMillis())); - deleteDto.setPreRegistrationId("12345678909876"); - deleteList.add(deleteDto); - Mockito.when(bookingDAO.deleteByPreRegistrationId(Mockito.anyString())).thenReturn(0); - - MainResponseDTO response = new MainResponseDTO<>(); - response.setErrors(null); - response.setResponse(deleteDto); - response.setResponsetime(serviceUtil.getCurrentResponseTime()); - - } - - @Test - public void getBookedPreIdsByDateTest() { - MainResponseDTO response = new MainResponseDTO<>(); - List preIds = new ArrayList<>(); - List details = new ArrayList<>(); - details.add("98746563542672"); - - preIds.add("98746563542672"); - response.setResponse("98746563542672"); - response.setVersion("1.0"); - - LocalDate fromDate = LocalDate.now(); - - LocalDate toDate = LocalDate.now().plusDays(30); - Map> idsWithSlotTime = new HashMap>(); - Mockito.when(bookingDAO.findByBookingDateBetweenAndRegCenterId(fromDate, toDate, "10001", idsWithSlotTime)) - .thenReturn(details); - - MainResponseDTO actualRes = service - .getBookedPreRegistrationByDate(fromDate.toString(), toDate.toString(), "10001"); - assertEquals("1.0", response.getVersion()); - - } - - @Test(expected = BookingDataNotFoundException.class) - public void getApplicationByDateFailureTest() { - List preids = new ArrayList<>(); - preids.add(""); - LocalDate fromDate = LocalDate.now(); - LocalDate toDate = LocalDate.now().plusDays(30); - Map> idsWithSlotTime = new HashMap>(); - Mockito.when( - serviceUtil.validateFromDateAndToDate(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(true); - Mockito.when(bookingDAO.findByBookingDateBetweenAndRegCenterId(fromDate, toDate, "10001", idsWithSlotTime)) - .thenThrow(new BookingDataNotFoundException("", "", new Throwable())); - service.getBookedPreRegistrationByDate(fromDate.toString(), toDate.toString(), "10001"); - } - - @Test(expected = AvailablityNotFoundException.class) - public void checkSlotAvailabilityTest() { - RegistrationCenterDto centerDto = new RegistrationCenterDto(); - List availablityList = new ArrayList<>(); - AvailibityEntity entity = new AvailibityEntity(); - entity.setAvailableKiosks(3); - entity.setRegcntrId("10001"); - availablityList.add(entity); - List centerList = new ArrayList<>(); - centerDto.setId("10001"); - centerDto.setLangCode("eng"); - centerDto.setCenterStartTime(startTime); - centerDto.setCenterEndTime(endTime); - centerDto.setPerKioskProcessTime(perKioskTime); - centerDto.setLunchStartTime(LunchStartTime); - centerDto.setLunchEndTime(LunchEndTime); - centerDto.setNumberOfKiosks((short) 4); - centerList.add(centerDto); - regCenDto.setRegistrationCenters(centerList); - RegistrationCenterHolidayDto CenholidayDto = new RegistrationCenterHolidayDto(); - HolidayDto holiday = new HolidayDto(); - List holidayList = new ArrayList<>(); - holiday.setHolidayDate(LocalDate.now().plusDays(30).toString()); - holidayList.add(holiday); - CenholidayDto.setHolidays(holidayList); - List regCenterList = new ArrayList<>(); - regCenterList.add("10001"); - List insertedDate = new ArrayList<>(); - insertedDate.add(LocalDate.now().plusDays(20)); - - ResponseWrapper resp = new ResponseWrapper<>(); - resp.setResponse(regCenDto); - - BookingRequestDTO successBookDto = new BookingRequestDTO(); - successBookDto.setRegistrationCenterId("10001"); - successBookDto.setSlotFromTime(LocalTime.of(9, 0).toString()); - successBookDto.setSlotToTime(LocalTime.of(9, 15).toString()); - successBookDto.setRegDate(LocalDate.now().plusDays(30).toString()); - - AvailibityEntity availableEntityNull = new AvailibityEntity(); - availableEntityNull.setAvailableKiosks(0); - availableEntityNull.setRegcntrId("1"); - availableEntityNull.setRegDate(LocalDate.now().plusDays(20)); - availableEntityNull.setCrBy("John Doe"); - availableEntityNull.setCrDate(DateUtils2.parseDateToLocalDateTime(new Date())); - availableEntityNull.setDeleted(false); - - Mockito.when(bookingDAO.updateAvailibityEntity(availableEntity)).thenReturn(availableEntity); - Mockito.when(serviceUtil.mandatoryParameterCheck(Mockito.anyString(), Mockito.any())).thenReturn(true); - Mockito.when(serviceUtil.validateAppointmentDate(Mockito.any())).thenReturn(true); - Mockito.when(serviceUtil.isKiosksAvailable(Mockito.any())).thenReturn(true); - Mockito.when(serviceUtil.getApplicationBookingStatus("23587986034785")).thenReturn("Booked"); - Mockito.when(serviceUtil.getRegCenterMasterData("10001")).thenReturn(centerList); - Mockito.when(bookingDAO.findRegCenter(Mockito.any())).thenReturn(regCenterList); - Mockito.when(bookingDAO.findByRegDateAndRegcntrIdAndFromTimeAndToTime(Mockito.any(), Mockito.anyString(), - Mockito.any(), Mockito.any())).thenReturn(availableEntityNull); - service.checkSlotAvailability(successBookDto); - } - - @Test - public void deleteOldBookingTest() { - int count = 1; - Mockito.when(bookingDAO.deleteByPreRegistrationId("12345678909876")).thenReturn(count); - boolean flag = service.deleteOldBooking("12345678909876"); - assertEquals(true, flag); - } - - @Test(expected = RecordFailedToDeleteException.class) - public void deleteOldBookingFailTest() { - RecordFailedToDeleteException exception = new RecordFailedToDeleteException( - ErrorCodes.PRG_BOOK_RCI_028.getCode(), - ErrorMessages.FAILED_TO_DELETE_THE_PRE_REGISTRATION_RECORD.getMessage()); - Mockito.when(service.deleteOldBooking("12345678909876")).thenThrow(exception); - service.deleteOldBooking("12345678909876"); - - } - - @Test(expected = AvailablityNotFoundException.class) - public void increaseAvailabilityTest() { - - BookingRequestDTO successBookDto = new BookingRequestDTO(); - successBookDto.setRegistrationCenterId("1"); - successBookDto.setSlotFromTime(LocalTime.of(9, 0).toString()); - successBookDto.setSlotToTime(LocalTime.of(9, 15).toString()); - successBookDto.setRegDate(LocalDate.now().plusDays(30).toString()); - AvailablityNotFoundException exception = new AvailablityNotFoundException( - ErrorCodes.PRG_BOOK_RCI_002.toString(), - ErrorMessages.AVAILABILITY_NOT_FOUND_FOR_THE_SELECTED_TIME.toString()); - Mockito.when(bookingDAO.findByRegDateAndRegcntrIdAndFromTimeAndToTime(Mockito.any(), Mockito.anyString(), - Mockito.any(), Mockito.any())).thenThrow(exception); - service.increaseAvailability(successBookDto); - } - - @SuppressWarnings("unchecked") - @Test - public void successBookAppointmentException() { - - InvalidRequestParameterException ex = new InvalidRequestParameterException( - ErrorCodes.PRG_BOOK_RCI_031.getCode(), - ErrorMessages.INVALID_BOOKING_DATE_TIME.getMessage() + " found for preregistration id - " - + requestMap.get(RequestCodes.PRE_REGISTRAION_ID.getCode()), - null); - MainRequestDTO bookingRequestDTOs = new MainRequestDTO<>(); - List successBookDtoList = new ArrayList<>(); - BookingRequestDTO successBookDto = new BookingRequestDTO(); - successBookDto.setRegistrationCenterId("1"); - successBookDto.setSlotFromTime(LocalTime.of(9, 0).toString()); - successBookDto.setSlotToTime(LocalTime.of(9, 0).toString().toString()); - successBookDto.setRegDate(LocalDate.now().plusDays(30).toString()); - successBookDtoList.add(successBookDto); - bookingRequestDTOs.setId("mosip.preregistration.booking.book"); - bookingRequestDTOs.setVersion("1.0"); - bookingRequestDTOs.setRequesttime(new Date()); - bookingRequestDTOs.setRequest(successBookDto); - List statusListrebook = new ArrayList<>(); - - PreRegistartionStatusDTO preRegistartionStatus = new PreRegistartionStatusDTO(); - preRegistartionStatus.setStatusCode(StatusCodes.BOOKED.getCode()); - preRegistartionStatus.setPreRegistartionId(bookingPreId); - preRegResponse.setResponse(preRegistartionStatus); - statusListrebook.add(preRegistartionStatus); - MainResponseDTO preRegResponseRebook = new MainResponseDTO(); - preRegResponseRebook.setErrors(null); - preRegResponseRebook.setResponse(preRegistartionStatus); - - requestValidatorFlag = validationUtil.requestValidator(bookingRequestDTOs); - - Mockito.when(serviceUtil.mandatoryParameterCheck(Mockito.anyString(), Mockito.any())).thenReturn(true); -// Mockito.when(serviceUtil.validateAppointmentDate(Mockito.any())).thenThrow(ex); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void successBookAppointmentForExpired() { - - MainRequestDTO bookingRequestDTOs = new MainRequestDTO<>(); - List successBookDtoList = new ArrayList<>(); - BookingRequestDTO successBookDto = new BookingRequestDTO(); - successBookDto.setRegistrationCenterId("1"); - successBookDto.setSlotFromTime(LocalTime.of(9, 0).toString()); - successBookDto.setSlotToTime(LocalTime.of(9, 15).toString()); - successBookDto.setRegDate(LocalDate.now().plusDays(30).toString()); - successBookDtoList.add(successBookDto); - bookingRequestDTOs.setId("mosip.preregistration.booking.book"); - bookingRequestDTOs.setVersion("1.0"); - bookingRequestDTOs.setRequesttime(new Date()); - bookingRequestDTOs.setRequest(successBookDto); - - availableEntity.setAvailableKiosks(3); - availableEntity.setRegcntrId("1"); - availableEntity.setRegDate(LocalDate.now().plusDays(30)); - availableEntity.setToTime(LocalTime.of(9, 0)); - availableEntity.setFromTime(LocalTime.of(9, 0)); - availableEntity.setCrBy("John Doe"); - availableEntity.setCrDate(DateUtils2.parseDateToLocalDateTime(new Date())); - availableEntity.setDeleted(false); - List statusListrebook = new ArrayList<>(); - - PreRegistartionStatusDTO preRegistartionStatus = new PreRegistartionStatusDTO(); - preRegistartionStatus.setStatusCode(StatusCodes.BOOKED.getCode()); - preRegistartionStatus.setPreRegistartionId(bookingPreId); - preRegResponse.setResponse(preRegistartionStatus); - statusListrebook.add(preRegistartionStatus); - MainResponseDTO preRegResponseRebook = new MainResponseDTO(); - preRegResponseRebook.setErrors(null); - preRegResponseRebook.setResponse(preRegistartionStatus); - Mockito.when(bookingDAO.findByRegDateAndRegcntrIdAndFromTimeAndToTime(Mockito.any(), Mockito.any(), - Mockito.any(), Mockito.any())).thenReturn(availableEntity); - - requestValidatorFlag = validationUtil.requestValidator(bookingRequestDTOs); - RegistrationCenterDto centerDto = new RegistrationCenterDto(); - List centerList = new ArrayList<>(); - centerDto.setId("10001"); - centerDto.setLangCode("eng"); - centerDto.setCenterStartTime(startTime); - centerDto.setCenterEndTime(endTime); - centerDto.setPerKioskProcessTime(perKioskTime); - centerDto.setLunchStartTime(LunchStartTime); - centerDto.setLunchEndTime(LunchEndTime); - centerDto.setNumberOfKiosks((short) 4); - centerList.add(centerDto); - Mockito.when(bookingDAO.updateAvailibityEntity(availableEntity)).thenReturn(availableEntity); - Mockito.when(serviceUtil.mandatoryParameterCheck(Mockito.anyString(), Mockito.any())).thenReturn(true); - Mockito.when(serviceUtil.validateAppointmentDate(Mockito.any())).thenReturn(true); - Mockito.when(serviceUtil.isKiosksAvailable(Mockito.any())).thenReturn(true); - Mockito.when(serviceUtil.getApplicationBookingStatus("23587986034785")).thenReturn("Expired"); - Mockito.when(serviceUtil.getRegCenterMasterData("10001")).thenReturn(centerList); - // Update status - RegistrationBookingEntity bookingEntity2 = new RegistrationBookingEntity(); - //bookingEntity2.setBookingPK(new RegistrationBookingPK(DateUtils2.parseDateToLocalDateTime(new Date()))); - bookingEntity2.setBookingDateTime(DateUtils2.parseDateToLocalDateTime(new Date())); - bookingEntity2.setPreregistrationId(bookingPreId); - bookingEntity2.setRegistrationCenterId(oldBooking.getRegistrationCenterId()); - bookingEntity2.setLangCode("12L"); - bookingEntity2.setCrBy("987654321"); - bookingEntity2.setCrDate(DateUtils2.parseDateToLocalDateTime(new Date())); - bookingEntity2.setRegDate(LocalDate.now().plusDays(30)); - bookingEntity2.setSlotFromTime(LocalTime.of(9, 0)); - bookingEntity2.setSlotToTime(LocalTime.of(9, 0)); - - MainResponseDTO mainResponseDTO = new MainResponseDTO<>(); - mainResponseDTO.setErrors(null); - mainResponseDTO.setResponse(bookingEntity2); - - Mockito.when(bookingDAO.findByPreRegistrationId("23587986034785")).thenReturn(bookingEntity2); - Mockito.when(bookingDAO.updateAvailibityEntity(availableEntity)).thenReturn(availableEntity); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void successMultiBookAppointmentExpired() { - - multiBookingListDto.add(multiBookingRequestDto1); - multiBookingListDto.add(multiBookingRequestDto2); - - MultiBookingRequest multiBookingRequest = new MultiBookingRequest(); - multiBookingRequest.setBookingRequest(multiBookingListDto); - responseDto.setResponsetime(serviceUtil.getCurrentResponseTime()); - - BookingStatusDTO bookingStatusDTO1 = new BookingStatusDTO(); - bookingStatusDTO1.setBookingMessage("Appointment booked successfully"); - - BookingStatusDTO bookingStatusDTO2 = new BookingStatusDTO(); - bookingStatusDTO2.setBookingMessage("Appointment booked successfully"); - - List bookingStatusDTOs = new ArrayList<>(); - bookingStatusDTOs.add(bookingStatusDTO1); - bookingStatusDTOs.add(bookingStatusDTO2); - - MainRequestDTO bookingRequestDTOs = new MainRequestDTO<>(); - MultiBookingRequest bookingRequest = new MultiBookingRequest(); - List successBookDtoList = new ArrayList<>(); - MultiBookingRequestDTO successBookDto1 = new MultiBookingRequestDTO(); - successBookDto1.setPreRegistrationId("23587986034785"); - successBookDto1.setRegistrationCenterId("1"); - successBookDto1.setSlotFromTime(LocalTime.of(9, 0).toString()); - successBookDto1.setSlotToTime(LocalTime.of(9, 15).toString()); - successBookDto1.setRegDate(LocalDate.now().plusDays(30).toString()); - successBookDtoList.add(successBookDto1); - bookingRequest.setBookingRequest(successBookDtoList); - bookingRequestDTOs.setRequest(bookingRequest); - bookingRequestDTOs.setId("mosip.preregistration.booking.book"); - bookingRequestDTOs.setVersion("1.0"); - bookingRequestDTOs.setRequesttime(new Date()); - - availableEntity.setAvailableKiosks(3); - availableEntity.setRegcntrId("1"); - availableEntity.setRegDate(LocalDate.now().plusDays(30)); - availableEntity.setToTime(LocalTime.of(9, 0)); - availableEntity.setFromTime(LocalTime.of(9, 15)); - availableEntity.setCrBy("John Doe"); - availableEntity.setCrDate(DateUtils2.parseDateToLocalDateTime(new Date())); - availableEntity.setDeleted(false); - List statusListrebook = new ArrayList<>(); - - PreRegistartionStatusDTO preRegistartionStatus = new PreRegistartionStatusDTO(); - preRegistartionStatus.setStatusCode(StatusCodes.BOOKED.getCode()); - preRegistartionStatus.setPreRegistartionId(bookingPreId); - preRegResponse.setResponse(preRegistartionStatus); - statusListrebook.add(preRegistartionStatus); - MainResponseDTO preRegResponseRebook = new MainResponseDTO(); - preRegResponseRebook.setErrors(null); - preRegResponseRebook.setResponse(preRegistartionStatus); - Mockito.when(bookingDAO.findByRegDateAndRegcntrIdAndFromTimeAndToTime(Mockito.any(), Mockito.any(), - Mockito.any(), Mockito.any())).thenReturn(availableEntity); - - requestValidatorFlag = validationUtil.requestValidator(bookingRequestDTOs); - - // Update status - RegistrationBookingEntity bookingEntity2 = new RegistrationBookingEntity(); - //bookingEntity2.setBookingPK(new RegistrationBookingPK(DateUtils2.parseDateToLocalDateTime(new Date()))); - bookingEntity2.setBookingDateTime(DateUtils2.parseDateToLocalDateTime(new Date())); - bookingEntity2.setPreregistrationId(bookingPreId); - bookingEntity2.setRegistrationCenterId(oldBooking.getRegistrationCenterId()); - bookingEntity2.setLangCode("eng"); - bookingEntity2.setCrBy("John Doe"); - bookingEntity2.setCrDate(DateUtils2.parseDateToLocalDateTime(new Date())); - bookingEntity2.setRegDate(LocalDate.now().plusDays(30)); - bookingEntity2.setSlotFromTime(LocalTime.of(9, 0)); - bookingEntity2.setSlotToTime(LocalTime.of(9, 15)); - - RegistrationCenterDto centerDto = new RegistrationCenterDto(); - List centerList = new ArrayList<>(); - centerDto.setId("10001"); - centerDto.setLangCode("eng"); - centerDto.setCenterStartTime(startTime); - centerDto.setCenterEndTime(endTime); - centerDto.setPerKioskProcessTime(perKioskTime); - centerDto.setLunchStartTime(LunchStartTime); - centerDto.setLunchEndTime(LunchEndTime); - centerDto.setNumberOfKiosks((short) 4); - centerList.add(centerDto); - - Mockito.when(bookingDAO.findByPreRegistrationId("23587986034785")).thenReturn(bookingEntity2); - Mockito.when(bookingDAO.updateAvailibityEntity(availableEntity)).thenReturn(availableEntity); - Mockito.when(serviceUtil.mandatoryParameterCheck(Mockito.anyString(), Mockito.any())).thenReturn(true); - Mockito.when(serviceUtil.validateAppointmentDate(Mockito.any())).thenReturn(true); - Mockito.when(serviceUtil.isKiosksAvailable(Mockito.any())).thenReturn(true); - Mockito.when(serviceUtil.getApplicationBookingStatus("23587986034785")).thenReturn("Expired"); - Mockito.when(serviceUtil.getRegCenterMasterData("10001")).thenReturn(centerList); - - MainResponseDTO mainResponseDTO = new MainResponseDTO<>(); - mainResponseDTO.setErrors(null); - mainResponseDTO.setResponse(bookingEntity2); - Mockito.when(bookingDAO.findByPreRegistrationId("23587986034785")).thenReturn(bookingEntity2); - Mockito.when(bookingDAO.updateAvailibityEntity(availableEntity)).thenReturn(availableEntity); - -// MainResponseDTO response = service.bookMultiAppointment(bookingRequestDTOs); -// assertNotNull(response.getResponse().getBookingStatusResponse().get(0).getBookingMessage()); - } - - @Test - public void successMultiBookAppointmentException() { - InvalidRequestParameterException ex = new InvalidRequestParameterException( - ErrorCodes.PRG_BOOK_RCI_031.getCode(), - ErrorMessages.INVALID_BOOKING_DATE_TIME.getMessage() + " found for preregistration id - " - + requestMap.get(RequestCodes.PRE_REGISTRAION_ID.getCode()), - null); - multiBookingListDto.add(multiBookingRequestDto1); - multiBookingListDto.add(multiBookingRequestDto2); - - MultiBookingRequest multiBookingRequest = new MultiBookingRequest(); - multiBookingRequest.setBookingRequest(multiBookingListDto); - responseDto.setResponsetime(serviceUtil.getCurrentResponseTime()); - - BookingStatusDTO bookingStatusDTO1 = new BookingStatusDTO(); - bookingStatusDTO1.setBookingMessage("Appointment booked successfully"); - - BookingStatusDTO bookingStatusDTO2 = new BookingStatusDTO(); - bookingStatusDTO2.setBookingMessage("Appointment booked successfully"); - - List bookingStatusDTOs = new ArrayList<>(); - bookingStatusDTOs.add(bookingStatusDTO1); - bookingStatusDTOs.add(bookingStatusDTO2); - - MainRequestDTO bookingRequestDTOs = new MainRequestDTO<>(); - MultiBookingRequest bookingRequest = new MultiBookingRequest(); - List successBookDtoList = new ArrayList<>(); - MultiBookingRequestDTO successBookDto1 = new MultiBookingRequestDTO(); - successBookDto1.setPreRegistrationId("23587986034785"); - successBookDto1.setRegistrationCenterId("1"); - successBookDto1.setSlotFromTime(LocalTime.of(9, 0).toString()); - successBookDto1.setSlotToTime(LocalTime.of(9, 15).toString()); - successBookDto1.setRegDate(LocalDate.now().plusDays(30).toString()); - successBookDtoList.add(successBookDto1); - bookingRequest.setBookingRequest(successBookDtoList); - bookingRequestDTOs.setRequest(bookingRequest); - bookingRequestDTOs.setId("mosip.preregistration.booking.book"); - bookingRequestDTOs.setVersion("1.0"); - bookingRequestDTOs.setRequesttime(new Date()); - - availableEntity.setAvailableKiosks(3); - availableEntity.setRegcntrId("1"); - availableEntity.setRegDate(LocalDate.now().plusDays(30)); - availableEntity.setToTime(LocalTime.of(9, 0)); - availableEntity.setFromTime(LocalTime.of(9, 15)); - availableEntity.setCrBy("John Doe"); - availableEntity.setCrDate(DateUtils2.parseDateToLocalDateTime(new Date())); - availableEntity.setDeleted(false); - requestValidatorFlag = validationUtil.requestValidator(bookingRequestDTOs); - - Mockito.when(serviceUtil.validateAppointmentDate(Mockito.any())).thenThrow(ex); - - } - -} diff --git a/pre-registration-booking-service/src/test/java/io/mosip/preregistration/booking/test/service/util/BookingServiceUtilTest.java b/pre-registration-booking-service/src/test/java/io/mosip/preregistration/booking/test/service/util/BookingServiceUtilTest.java deleted file mode 100644 index af64ed332f8..00000000000 --- a/pre-registration-booking-service/src/test/java/io/mosip/preregistration/booking/test/service/util/BookingServiceUtilTest.java +++ /dev/null @@ -1,691 +0,0 @@ -package io.mosip.preregistration.booking.test.service.util; - -import static org.junit.Assert.assertEquals; - -import java.text.SimpleDateFormat; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.LocalTime; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import io.mosip.preregistration.booking.exception.*; -import io.mosip.preregistration.core.exception.UserLookupException; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.bean.override.mockito.MockitoBean; -import org.springframework.core.ParameterizedTypeReference; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -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.test.context.junit4.SpringRunner; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; -import org.springframework.web.client.HttpClientErrorException; -import org.springframework.web.client.RestTemplate; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.kernel.core.authmanager.authadapter.model.AuthUserDetails; -import io.mosip.kernel.core.util.DateUtils2; -import io.mosip.preregistration.booking.codes.RequestCodes; -import io.mosip.preregistration.booking.dto.BookingRequestDTO; -import io.mosip.preregistration.booking.dto.CancelBookingDTO; -import io.mosip.preregistration.booking.dto.DateTimeDto; -import io.mosip.preregistration.booking.dto.RegistrationCenterDto; -import io.mosip.preregistration.booking.dto.RegistrationCenterResponseDto; -import io.mosip.preregistration.booking.dto.SlotDto; -import io.mosip.preregistration.booking.entity.AvailibityEntity; -import io.mosip.preregistration.booking.repository.BookingAvailabilityRepository; -import io.mosip.preregistration.booking.repository.RegistrationBookingRepository; -import io.mosip.preregistration.booking.repository.impl.BookingDAO; -import io.mosip.preregistration.booking.service.util.BookingServiceUtil; -import io.mosip.preregistration.core.common.dto.BookingRegistrationDTO; -import io.mosip.preregistration.core.common.dto.MainRequestDTO; -import io.mosip.preregistration.core.common.dto.NotificationDTO; -import io.mosip.preregistration.core.common.dto.ResponseWrapper; -import io.mosip.preregistration.core.common.entity.RegistrationBookingEntity; -import io.mosip.preregistration.core.common.service.UserDetailsService; -import io.mosip.preregistration.core.exception.MasterDataNotAvailableException; -import io.mosip.preregistration.core.exception.RestCallException; -import io.mosip.preregistration.core.util.RequestValidator; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = { BookingServiceUtil.class }) -public class BookingServiceUtilTest { - - @MockitoBean - private BookingAvailabilityRepository bookingAvailabilityRepository; - - @MockitoBean - private RegistrationBookingRepository registrationBookingRepository; - - @MockitoBean(name = "selfTokenRestTemplate") - RestTemplate restTemplate; - - @MockitoBean - private RequestValidator requestValidator; - - @MockitoBean - ObjectMapper mapper; - - @Autowired - private BookingServiceUtil serviceUtil; - - @MockitoBean - private BookingDAO bookingDAO; - - @MockitoBean - private UserDetailsService userDetailsService; - - @Mock - private AuthUserDetails authUserDetails; - - @Mock - SecurityContextHolder securityContextHolder; - RegistrationCenterResponseDto regCenDto = new RegistrationCenterResponseDto(); - RegistrationCenterDto centerDto = new RegistrationCenterDto(); - List centerList = new ArrayList<>(); - - LocalTime startTime; - LocalTime endTime; - LocalTime perKioskTime; - LocalTime LunchStartTime; - LocalTime LunchEndTime; - LocalTime localTime1; - LocalTime localTime2; - DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); - - @Before - public void setup() throws Exception { - - String date3 = "2016-11-09 00:20:00"; - String date4 = "2016-11-09 13:00:00"; - String date5 = "2016-11-09 14:20:00"; - String date1 = "2016-11-09 09:00:00"; - String date2 = "2016-11-09 09:20:00"; - LocalDateTime localDateTime1 = LocalDateTime.parse(date1, format); - LocalDateTime localDateTime2 = LocalDateTime.parse(date2, format); - localTime1 = localDateTime1.toLocalTime(); - localTime2 = localDateTime2.toLocalTime(); - LocalDateTime localDateTime3 = LocalDateTime.parse(date3, format); - startTime = localDateTime1.toLocalTime(); - endTime = localDateTime2.toLocalTime(); - perKioskTime = localDateTime3.toLocalTime(); - LunchStartTime = LocalDateTime.parse(date4, format).toLocalTime(); - LunchEndTime = LocalDateTime.parse(date5, format).toLocalTime(); - AuthUserDetails applicationUser = Mockito.mock(AuthUserDetails.class); - Authentication authentication = Mockito.mock(Authentication.class); - SecurityContext securityContext = Mockito.mock(SecurityContext.class); - Mockito.when(securityContext.getAuthentication()).thenReturn(authentication); - SecurityContextHolder.setContext(securityContext); - Mockito.when(SecurityContextHolder.getContext().getAuthentication().getPrincipal()).thenReturn(applicationUser); - Mockito.when(applicationUser.getUserId()).thenReturn("test-user"); - Mockito.when(userDetailsService.getOrCreateInternalUserId("test-user")) - .thenReturn("00000000-0000-0000-0000-000000000001"); - centerDto.setId("10001"); - centerDto.setLangCode("eng"); - centerDto.setCenterStartTime(startTime); - centerDto.setCenterEndTime(endTime); - centerDto.setPerKioskProcessTime(perKioskTime); - centerDto.setLunchStartTime(LunchStartTime); - centerDto.setLunchEndTime(LunchEndTime); - centerDto.setNumberOfKiosks((short) 4); - centerList.add(centerDto); - regCenDto.setRegistrationCenters(centerList); - } - - @Test - public void mandatoryParameterCheckTest() { - String preRegistrationId = "23587986034785"; - BookingRequestDTO bookingRequestDTO = new BookingRequestDTO(); - bookingRequestDTO.setRegistrationCenterId("1"); - bookingRequestDTO.setSlotFromTime("09:00"); - bookingRequestDTO.setSlotToTime("09:13"); - bookingRequestDTO.setRegDate("2018-12-06"); - - boolean flag = serviceUtil.mandatoryParameterCheck(preRegistrationId, bookingRequestDTO); - assertEquals(true, flag); - } - - @Test(expected = BookingPreIdNotFoundException.class) - public void regIdNullCheckTest() { - String preRegistrationId = null; - BookingRequestDTO bookingRequestDTO = new BookingRequestDTO(); - bookingRequestDTO.setRegistrationCenterId("1"); - bookingRequestDTO.setSlotFromTime("09:00"); - bookingRequestDTO.setSlotToTime("09:13"); - bookingRequestDTO.setRegDate("2018-12-06"); - - serviceUtil.mandatoryParameterCheck(preRegistrationId, bookingRequestDTO); - - } - - @Test(expected = BookingRegistrationCenterIdNotFoundException.class) - public void regCenterNullinOldBookingCheckTest() { - String preRegistrationId = "23587986034785"; - BookingRequestDTO bookingRequestDTO = new BookingRequestDTO(); - bookingRequestDTO.setRegistrationCenterId(null); - bookingRequestDTO.setSlotFromTime("09:00"); - bookingRequestDTO.setSlotToTime("09:13"); - bookingRequestDTO.setRegDate("2018-12-06"); - - serviceUtil.mandatoryParameterCheck(preRegistrationId, bookingRequestDTO); - - } - - @Test(expected = BookingTimeSlotNotSeletectedException.class) - public void slotNullinOldBookingCheckTest() { - String preRegistrationId = "23587986034785"; - BookingRequestDTO bookingRequestDTO = new BookingRequestDTO(); - bookingRequestDTO.setRegistrationCenterId("1"); - bookingRequestDTO.setSlotFromTime(null); - bookingRequestDTO.setSlotToTime(null); - bookingRequestDTO.setRegDate("2018-12-06"); - - serviceUtil.mandatoryParameterCheck(preRegistrationId, bookingRequestDTO); - - } - - @Test(expected = BookingDateNotSeletectedException.class) - public void regDateNullinOldBookingCheckTest() { - String preRegistrationId = "23587986034785"; - BookingRequestDTO bookingRequestDTO = new BookingRequestDTO(); - bookingRequestDTO.setRegistrationCenterId("1"); - bookingRequestDTO.setSlotFromTime("09:00"); - bookingRequestDTO.setSlotToTime("09:13"); - bookingRequestDTO.setRegDate(null); - - serviceUtil.mandatoryParameterCheck(preRegistrationId, bookingRequestDTO); - - } - - @Test(expected = BookingRegistrationCenterIdNotFoundException.class) - public void regCenterNullinNewBookingCheckTest() { - String preRegistrationId = "23587986034785"; - - BookingRequestDTO bookingRequestDTO = new BookingRequestDTO(); - bookingRequestDTO.setRegistrationCenterId(null); - bookingRequestDTO.setSlotFromTime("09:00"); - bookingRequestDTO.setSlotToTime("09:13"); - bookingRequestDTO.setRegDate("2018-12-06"); - - serviceUtil.mandatoryParameterCheck(preRegistrationId, bookingRequestDTO); - - } - - @Test(expected = BookingTimeSlotNotSeletectedException.class) - public void slotNullinNewBookingCheckTest() { - String preRegistrationId = "23587986034785"; - BookingRequestDTO bookingRequestDTO = new BookingRequestDTO(); - bookingRequestDTO.setRegistrationCenterId("10"); - bookingRequestDTO.setSlotFromTime(null); - bookingRequestDTO.setSlotToTime(null); - bookingRequestDTO.setRegDate("2018-12-06"); - - serviceUtil.mandatoryParameterCheck(preRegistrationId, bookingRequestDTO); - - } - - @Test(expected = BookingDateNotSeletectedException.class) - public void bookingDateNotSeletectedExceptionTest() { - String preRegistrationId = "23587986034785"; - BookingRequestDTO bookingRequestDTO = new BookingRequestDTO(); - bookingRequestDTO.setRegistrationCenterId("10"); - bookingRequestDTO.setSlotFromTime("09:00"); - bookingRequestDTO.setSlotToTime("09:13"); - bookingRequestDTO.setRegDate(null); - - serviceUtil.mandatoryParameterCheck(preRegistrationId, bookingRequestDTO); - - } - - @Test(expected = AppointmentReBookingFailedException.class) - public void appointmentReBookingFailedExceptionTest() { - BookingRegistrationDTO oldBooking = new BookingRegistrationDTO(); - oldBooking.setRegistrationCenterId("1"); - oldBooking.setSlotFromTime("09:00"); - oldBooking.setSlotToTime("09:13"); - oldBooking.setRegDate("2018-12-06"); - BookingRegistrationDTO newBooking = new BookingRegistrationDTO(); - newBooking.setRegistrationCenterId("1"); - newBooking.setSlotFromTime("09:00"); - newBooking.setSlotToTime("09:13"); - newBooking.setRegDate("2018-12-06"); - - serviceUtil.isNotDuplicate(oldBooking, newBooking); - - } - - @Test - public void cancelBookingDtoSetterTest() { - String preRegistrationId = "23587986034785"; - BookingRegistrationDTO bookingRegistrationDTO = new BookingRegistrationDTO(); - bookingRegistrationDTO.setRegistrationCenterId("1"); - bookingRegistrationDTO.setSlotFromTime("09:00"); - bookingRegistrationDTO.setSlotToTime("09:13"); - bookingRegistrationDTO.setRegDate("2018-12-06"); - - CancelBookingDTO cancelBookingDTO = serviceUtil.cancelBookingDtoSetter(preRegistrationId, - bookingRegistrationDTO); - assertEquals("1", bookingRegistrationDTO.getRegistrationCenterId()); - } - - @Test - public void validateAppointmentDateTest() { - Calendar cal = Calendar.getInstance(); - cal.add(Calendar.DATE, 1); - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); - Map dateMap = new HashMap<>(); - dateMap.put(RequestCodes.REG_DATE.getCode(), sdf.format(cal.getTime())); - dateMap.put(RequestCodes.FROM_SLOT_TIME.getCode(), LocalTime.now().toString()); - boolean isValid = serviceUtil.validateAppointmentDate(dateMap); - assertEquals(Boolean.TRUE, isValid); - } - - @Ignore - @Test(expected = InvalidDateTimeFormatException.class) - public void validateAppointmentDateExceptionTest() { - Calendar cal = Calendar.getInstance(); - cal.add(Calendar.DATE, -1); - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); - Map dateMap = new HashMap<>(); - dateMap.put(RequestCodes.REG_DATE.getCode(), sdf.format(cal.getTime())); - dateMap.put(RequestCodes.FROM_SLOT_TIME.getCode(), LocalTime.now().toString()); - boolean isValid = serviceUtil.validateAppointmentDate(dateMap); - assertEquals(Boolean.FALSE, isValid); - } - - @Test(expected = InvalidDateTimeFormatException.class) - @Ignore - public void validateAppointmentTimeExceptionTest() { - Calendar cal = Calendar.getInstance(); - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); - Map dateMap = new HashMap<>(); - dateMap.put(RequestCodes.REG_DATE.getCode(), sdf.format(cal.getTime())); - dateMap.put(RequestCodes.FROM_SLOT_TIME.getCode(), LocalTime.now().minusMinutes(120).toString()); - boolean isValid = serviceUtil.validateAppointmentDate(dateMap); - assertEquals(Boolean.FALSE, isValid); - } - - @Test(expected = AvailablityNotFoundException.class) - public void AvailablityNotFoundException() { - AvailibityEntity availableEntity = new AvailibityEntity(); - availableEntity.setAvailableKiosks(0); - availableEntity.setRegcntrId("1"); - availableEntity.setRegDate(LocalDate.parse("2018-12-04")); - availableEntity.setCrBy("987654321"); - availableEntity.setCrDate(DateUtils2.parseDateToLocalDateTime(new Date())); - availableEntity.setDeleted(false); - serviceUtil.isKiosksAvailable(availableEntity); - } - - @Test(expected = BookingPreIdNotFoundException.class) - public void bookingPreIdNotFoundExceptionforCancelTest() { - - CancelBookingDTO cancelBookingDTO = new CancelBookingDTO(); - serviceUtil.mandatoryParameterCheckforCancel(null); - - } - - /* - * @Test(expected=BookingRegistrationCenterIdNotFoundException.class) public - * void bookingRegistrationCenterIdNotFoundExceptionforCancelTest() { - * - * CancelBookingDTO cancelBookingDTO = new CancelBookingDTO(); - * cancelBookingDTO.setRegistrationCenterId(null); - * serviceUtil.mandatoryParameterCheckforCancel("23587986034785"); - * - * } - */ - - /* - * @Test(expected=BookingDateNotSeletectedException.class) public void - * bookingDateNotSeletectedExceptionforCancelTest() { - * - * CancelBookingDTO cancelBookingDTO = new CancelBookingDTO(); - * cancelBookingDTO.setRegistrationCenterId("1"); - * cancelBookingDTO.setSlotFromTime("09:00"); - * cancelBookingDTO.setSlotToTime("09:13"); cancelBookingDTO.setRegDate(null); - * serviceUtil.mandatoryParameterCheckforCancel("23587986034785"); - * - * } - */ - - /* - * @Test(expected=BookingTimeSlotNotSeletectedException.class) public void - * bookingTimeSlotNotSeletectedExceptionforCancelTest() { - * - * CancelBookingDTO cancelBookingDTO = new CancelBookingDTO(); - * cancelBookingDTO.setRegistrationCenterId("1"); - * cancelBookingDTO.setRegDate("2018-12-06"); - * cancelBookingDTO.setSlotFromTime(null); cancelBookingDTO.setSlotToTime(null); - * serviceUtil.mandatoryParameterCheckforCancel("23587986034785"); - * - * } - */ - - @Test(expected = MasterDataNotAvailableException.class) - public void callRegCenterDateRestServiceTest() { - - RegistrationCenterResponseDto preRegResponse = new RegistrationCenterResponseDto(); - preRegResponse.setRegistrationCenters(null); - ResponseWrapper resp = new ResponseWrapper<>(); - resp.setResponse(preRegResponse); - ResponseEntity> res = new ResponseEntity<>(resp, HttpStatus.OK); - Mockito.when(restTemplate.exchange(Mockito.anyString(), Mockito.eq(HttpMethod.GET), Mockito.any(), - Mockito.eq(new ParameterizedTypeReference>() { - }))).thenReturn(res); - - serviceUtil.getRegCenterMasterData("10001"); - - } - - @Ignore - @Test(expected = RestCallException.class) - public void HttpClientErrorExceptionTest() { - HttpClientErrorException ex = new HttpClientErrorException(HttpStatus.OK); - Mockito.when(restTemplate.exchange(Mockito.anyString(), Mockito.eq(HttpMethod.GET), Mockito.any(), - Mockito.eq(new ParameterizedTypeReference>() { - }))).thenThrow(ex); - - serviceUtil.getRegCenterMasterData("10001"); - - } - - /* - * @Test(expected = DemographicStatusUpdationException.class) public void - * callUpdateStatusRestServiceTest() { - * - * Map map = new HashMap<>(); map.put("pre_rgistration_id", - * "23587986034785"); - * - * RestClientException ex = new RestClientException(null); - * MainResponseDTO preRegResponse = new MainResponseDTO<>(); - * preRegResponse.setResponse(null); ExceptionJSONInfoDTO err = new - * ExceptionJSONInfoDTO(); List errList = new - * ArrayList<>(); err.setErrorCode(ErrorCodes.PRG_BOOK_RCI_011.name()); - * err.setMessage(ErrorMessages.DEMOGRAPHIC_STATUS_UPDATION_FAILED.getMessage()) - * ; errList.add(err); preRegResponse.setErrors(errList); - * preRegResponse.setResponsetime(serviceUtil.getCurrentResponseTime()); - * MainResponseDTO updatePreRegistrationStatus = new - * MainResponseDTO<>(); updatePreRegistrationStatus.setErrors(errList); - * Mockito.when(serviceUtil.updatePreRegistrationStatus("23587986034785", - * "Pending_Appointment")) .thenReturn(updatePreRegistrationStatus); - * serviceUtil.updateDemographicStatus("23587986034785", "Pending_Appointment"); - * - * } - * - * @SuppressWarnings("unchecked") - * - * @Test(expected = BookingDataNotFoundException.class) public void - * callGetStatusRestServiceforCancelTest() { - * - * List statusList = new ArrayList<>(); - * PreRegistartionStatusDTO preRegistartionStatusDTO = new - * PreRegistartionStatusDTO(); - * - * @SuppressWarnings("rawtypes") MainResponseDTO preRegResponse = new - * MainResponseDTO(); - * preRegistartionStatusDTO.setStatusCode(StatusCodes.PENDING_APPOINTMENT. - * getCode()); preRegistartionStatusDTO.setPreRegistartionId("23587986034785"); - * statusList.add(preRegistartionStatusDTO); - * - * preRegResponse.setResponse(preRegistartionStatusDTO); - * preRegResponse.setErrors(null); - * preRegResponse.setResponsetime(serviceUtil.getCurrentResponseTime()); - * Mockito.when(serviceUtil.getApplicationStatus("23587986034785")).thenReturn( - * preRegResponse); serviceUtil.getDemographicStatusForCancel("23587986034785"); - * - * } - */ - /* - * @Test(expected = DemographicGetStatusException.class) public void - * callGetStatusRestServiceforCancel1Test() { - * - * @SuppressWarnings("rawtypes") MainResponseDTO preRegResponse = new - * MainResponseDTO(); ExceptionJSONInfoDTO err = new ExceptionJSONInfoDTO(); - * err.setErrorCode(ErrorCodes.PRG_BOOK_RCI_011.name()); - * err.setMessage(ErrorMessages.DEMOGRAPHIC_STATUS_UPDATION_FAILED.getMessage()) - * ; List list = new ArrayList<>(); list.add(err); - * preRegResponse.setErrors(list); - * preRegResponse.setResponsetime(serviceUtil.getCurrentResponseTime()); - * - * @SuppressWarnings("unchecked") - * ResponseEntity> res = new - * ResponseEntity<>(preRegResponse, HttpStatus.OK); - * Mockito.when(restTemplate.exchange(Mockito.anyString(), - * Mockito.eq(HttpMethod.GET), Mockito.any(), Mockito.eq(new - * ParameterizedTypeReference>() { }), - * Mockito.anyMap())).thenReturn(res); - * serviceUtil.getDemographicStatusForCancel("23587986034785"); - * - * } - */ - - /* - * @Test(expected = DemographicGetStatusException.class) public void - * callGetStatusRestService1Test() { MainResponseDTO - * getApplicationStatus = new MainResponseDTO<>(); List ex - * = new ArrayList(); ExceptionJSONInfoDTO err = new - * ExceptionJSONInfoDTO(); err.setErrorCode(ErrorCodes.PRG_BOOK_RCI_011.name()); - * err.setMessage(ErrorMessages.DEMOGRAPHIC_STATUS_UPDATION_FAILED.getMessage()) - * ; ex.add(err); getApplicationStatus.setErrors(ex); - * Mockito.when(serviceUtil.getApplicationStatus("23587986034785")).thenReturn( - * getApplicationStatus); serviceUtil.getDemographicStatus("23587986034785"); - * - * } - */ - - @Test - public void isValidRegCenterTest() { - ResponseWrapper resp = new ResponseWrapper<>(); - resp.setResponse(regCenDto); - ResponseEntity> res = new ResponseEntity<>(resp, HttpStatus.OK); - Mockito.when(restTemplate.exchange(Mockito.anyString(), Mockito.eq(HttpMethod.GET), Mockito.any(), - Mockito.eq(new ParameterizedTypeReference>() { - }))).thenReturn(res); - serviceUtil.isValidRegCenter("10001"); - } - - @Test(expected = RecordNotFoundException.class) - public void isValidRegCenterTestException() { - ResponseWrapper resp = new ResponseWrapper<>(); - regCenDto.getRegistrationCenters().get(0).setId("1"); - resp.setResponse(regCenDto); - ResponseEntity> res = new ResponseEntity<>(resp, HttpStatus.OK); - Mockito.when(restTemplate.exchange(Mockito.anyString(), Mockito.eq(HttpMethod.GET), Mockito.any(), - Mockito.eq(new ParameterizedTypeReference>() { - }))).thenReturn(res); - serviceUtil.isValidRegCenter("10001"); - } - - @Test - public void validateFromDateAndToDateTest() { - String format = "yyyy-MM-dd"; - String todate = "2019-11-15"; - String fromdate = "2019-11-05"; - serviceUtil.validateFromDateAndToDate(fromdate, todate, format); - } - - @Test(expected = InvalidDateTimeFormatException.class) - public void validateFromDateAndToDateTestEx1() { - String format = "yyyy-MM-dd"; - String todate = "2019-11-15"; - String fromdate = new Date().toString(); - serviceUtil.validateFromDateAndToDate(fromdate, todate, format); - } - - @Test(expected = InvalidDateTimeFormatException.class) - public void validateFromDateAndToDateTestEx2() { - String format = "yyyy-MM-dd"; - String todate = "2019-11-15"; - String fromdate = ""; - serviceUtil.validateFromDateAndToDate(fromdate, todate, format); - } - - @Test(expected = InvalidDateTimeFormatException.class) - public void validateFromDateAndToDateTestEx3() { - String format = "yyyy-MM-dd"; - String todate = "2019-11-05"; - String fromdate = "2019-11-15"; - serviceUtil.validateFromDateAndToDate(fromdate, todate, format); - } - - @Test(expected = NullPointerException.class) - public void emailNotificationTest() throws JsonProcessingException { - NotificationDTO dto = new NotificationDTO(); - dto.setEmailID("rajath@gmail.com"); - dto.setMobNum("9480548558"); - dto.setAdditionalRecipient(false); - MultiValueMap emailMap = new LinkedMultiValueMap<>(); - emailMap.add("NotificationRequestDTO", mapper.writeValueAsString(dto)); - emailMap.add("langCode", "eng"); - HttpHeaders headers = new HttpHeaders(); - HttpEntity> httpEntity = new HttpEntity<>(emailMap, headers); - ResponseEntity res = new ResponseEntity<>("Success", HttpStatus.OK); - Mockito.when(restTemplate.exchange(Mockito.anyString(), Mockito.eq(HttpMethod.POST), Mockito.any(), - Mockito.eq(new ParameterizedTypeReference() { - }))).thenReturn(res); - serviceUtil.emailNotification(dto, "eng"); - } - - @Test - public void bookingEntitySetterTest() { - BookingRequestDTO bookingRequestDTO = new BookingRequestDTO(); - bookingRequestDTO.setRegistrationCenterId("1"); - bookingRequestDTO.setSlotFromTime("09:00"); - bookingRequestDTO.setSlotToTime("09:13"); - bookingRequestDTO.setRegDate("2018-12-06"); - serviceUtil.bookingEntitySetter("1234568687844744", bookingRequestDTO); - } - - @Test - public void bookingEntitySetterLegacyCrByTest() { - BookingRequestDTO bookingRequestDTO = new BookingRequestDTO(); - bookingRequestDTO.setRegistrationCenterId("1"); - bookingRequestDTO.setSlotFromTime("09:00"); - bookingRequestDTO.setSlotToTime("09:13"); - bookingRequestDTO.setRegDate("2018-12-06"); - RegistrationBookingEntity entity = serviceUtil.bookingEntitySetter("1234568687844744", bookingRequestDTO); - assertEquals("00000000-0000-0000-0000-000000000001", entity.getCrBy()); - } - - @Test(expected = AppointmentBookingFailedException.class) - public void bookingEntitySetterThrowsOnUuidResolutionFailureTest() { - Mockito.when(userDetailsService.getOrCreateInternalUserId("test-user")) - .thenThrow(new UserLookupException("PRG_CORE_REQ_024", "Failed to resolve internal user ID")); - BookingRequestDTO bookingRequestDTO = new BookingRequestDTO(); - bookingRequestDTO.setRegistrationCenterId("1"); - bookingRequestDTO.setSlotFromTime("09:00"); - bookingRequestDTO.setSlotToTime("09:13"); - bookingRequestDTO.setRegDate("2018-12-06"); - serviceUtil.bookingEntitySetter("1234568687844744", bookingRequestDTO); - } - - /** - * An absent authenticated user id must fail as an identity error rather than - * flowing through as a null crBy and tripping the NOT NULL constraint, which - * would surface to the caller as an opaque "table not accessible" error. - */ - @Test(expected = AppointmentBookingFailedException.class) - public void bookingEntitySetter_authenticatedUserIdAbsent_throwsAppointmentBookingFailed() { - AuthUserDetails principal = (AuthUserDetails) SecurityContextHolder.getContext().getAuthentication() - .getPrincipal(); - Mockito.when(principal.getUserId()).thenReturn(null); - BookingRequestDTO bookingRequestDTO = new BookingRequestDTO(); - bookingRequestDTO.setRegistrationCenterId("1"); - bookingRequestDTO.setSlotFromTime("09:00"); - bookingRequestDTO.setSlotToTime("09:13"); - bookingRequestDTO.setRegDate("2018-12-06"); - serviceUtil.bookingEntitySetter("1234568687844744", bookingRequestDTO); - } - - @Test - public void prepareRequestMapTest() { - MainRequestDTO requestDto = new MainRequestDTO<>(); - requestDto.setId("mosip.io.booking"); - requestDto.setVersion("1.0"); - requestDto.setRequest("98463784586348"); - Date date = new Date(); - requestDto.setRequesttime(date); - serviceUtil.prepareRequestMap(requestDto); - } - - @Test - public void slotSetter() { - List dateList = new ArrayList<>(); - SlotDto slots = new SlotDto(); - DateTimeDto dateDto = new DateTimeDto(); - List slotsList = new ArrayList<>(); - List availabilityList = new ArrayList<>(); - AvailibityEntity availableEntity = new AvailibityEntity(); - String date1 = "2016-11-09 09:00:00"; - String date2 = "2016-11-09 09:20:00"; - LocalDateTime localDateTime1 = LocalDateTime.parse(date1, format); - LocalDateTime localDateTime2 = LocalDateTime.parse(date2, format); - localTime1 = localDateTime1.toLocalTime(); - localTime2 = localDateTime2.toLocalTime(); - slots.setAvailability(4); - slots.setFromTime(localTime1); - slots.setToTime(localTime2); - slotsList.add(slots); - dateDto.setDate("2018-12-04"); - dateDto.setHoliday(false); - dateDto.setTimeSlots(slotsList); - dateList.add(dateDto); - availableEntity.setAvailableKiosks(4); - availableEntity.setRegcntrId("1"); - availableEntity.setRegDate(LocalDate.parse("2019-12-04")); - availableEntity.setToTime(localTime2); - availableEntity.setFromTime(localTime1); - availableEntity.setCrBy("987654321"); - availableEntity.setCrDate(DateUtils2.parseDateToLocalDateTime(new Date())); - availableEntity.setDeleted(false); - availabilityList.add(availableEntity); - serviceUtil.slotSetter(availableEntity.getRegDate(), dateList, dateDto, availabilityList); - } - - @Test(expected = TimeSpanException.class) - public void timeSpanCheckForCancel() { - LocalDateTime time = LocalDateTime.now(); - serviceUtil.timeSpanCheckForCancle(time); - } - - @Test - public void timeSpanCheckForCancel1() { - LocalDateTime time = LocalDateTime.now().plusDays(3); - serviceUtil.timeSpanCheckForCancle(time); - } - - @Test(expected = TimeSpanException.class) - public void timeSpanCheckForRebook() { - LocalDateTime time = LocalDateTime.now(); - serviceUtil.timeSpanCheckForRebook(time, new Date()); - } - - @Test - public void timeSpanCheckForRebook1() { - LocalDateTime time = LocalDateTime.now().plusDays(3); - serviceUtil.timeSpanCheckForRebook(time, new Date()); - } - -} - - diff --git a/pre-registration-booking-service/src/test/resources/application.properties b/pre-registration-booking-service/src/test/resources/application.properties deleted file mode 100644 index 4c5991c7926..00000000000 --- a/pre-registration-booking-service/src/test/resources/application.properties +++ /dev/null @@ -1,176 +0,0 @@ -# javax.persistence.jdbc.driver=org.h2.Driver -# javax.persistence.jdbc.url=jdbc:h2\:mem\:testdb;DB_CLOSE_DELAY=-1;INIT=RUNSCRIPT FROM 'classpath:create-schema.sql' -# javax.persistence.jdbc.user=sa -javax.persistence.jdbc.driver: org.postgresql.Driver -javax.persistence.jdbc.url=jdbc:postgresql://api-internal.dev1.mosip.net:5432/mosip_prereg -javax.persistence.jdbc.user: postgres -javax.persistence.jdbc.password= -mosip.kernel.objectstore.account-name=prereg -cancel.appoinment.template=cancel-appointment -hibernate.hbm2ddl.auto=update -hibernate.dialect=org.hibernate.dialect.H2Dialect -hibernate.show_sql=false -hibernate.format_sql=false -hibernate.connection.charSet=utf8 -hibernate.cache.use_second_level_cache=false -hibernate.cache.use_query_cache=false -hibernate.cache.use_structured_entries=false -hibernate.generate_statistics=false -notification.url=https://api-internal.dev1.mosip.net/notification/notify -mosip.supported-languages=eng,ara,fra -mosip.primary-language=eng -mosip.io.prid.url=https://api-internal.dev1.mosip.net/v1/pridgenerator/prid -# preregistration.country.specific.zoneId=GMT+05:30 -booking.resource.url=${dev.dns.url}/preregistration/v1 -preregistration.rebook.timespan = 24 -preregistration.cancel.timespan = 24 -preregistration.timespan.cancel=24 -preregistration.timespan.rebook=24 - -service.version=v1.0 -master.service.env=masterdata -demographic.service.env=demographic -demographic.service.version=v0.1 - -document.service.env=demographic -document.service.version=v0.1 - -int.dns.url=http://localhost:8086 -dev.dns.url=https://dev.mosip.net - -#Number of days for which time slot will be calculated -preregistration.availability.sync=7 - -#Number of days for display -preregistration.availability.noOfDays=7 - -#Number of days after which timeslots will be seen in UI -preregistration.booking.offset=2 -regCenter.url=http://localhost:8086/masterdata/v1.0/registrationcenters -holiday.url=http://localhost:8086/masterdata/v1.0/getregistrationcenterholidays/ -noOfKiosks=10 -documentUrl=http://localhost:9093/${document.service.env}/${document.service.version}/getDocument -email.acknowledgement.template=Email-Acknowledgement -cancel.appointment.email.subject=cancel-appointment-email-subject -email.acknowledgement.subject.template=Acknowledgement-email-subject -sms.acknowledgement.template=SMS-Acknowledgement -version=1.0 -id=mosip.pre-registration.booking.book -demographic.resource.url=http://localhost:9092/pre-registration/v1.0/applications - -#Pre-registration Id length -prereg_id.length=16 - -#Kernel Service URL for Encryption and decryption -cryptoResource.url=${dev.dns.url}/cryptomanager/v1.0 - -#Kernel service URL for Audit logging -audit.url=${dev.dns.url}/auditmanager/v1.0/audits - -#Kernel service URL for fetching templates -resource.template.url=${dev.dns.url}/masterdata/v1.0/templates - -#Kernel service URL for sending emails -emailResourse.url=${dev.dns.url}/emailnotifier/v1.0/email/send - -#Kernel service URL for sending sms -smsResourse.url=${dev.dns.url}/smsnotifier/v1.0/sms/send - -timeSpanCheckForRebook=24 -timeSpanCheckForCancel=24 -# UTC ISO Date Time Pattern -mosip.utc-datetime-pattern=yyyy-MM-dd'T'HH:mm:ss.SSS'Z' -mosip.id.validation.identity.dateOfBirth= -mosip.id.validation.identity.phone= -mosip.id.validation.identity.email= -mosip.id.validation.identity.postalCode= -mosip.id.validation.identity.CNIENumber= -mosip.id.validation.identity.phone.length=10 -mosip.id.validation.identity.email.length=50 -mosip.id.validation.identity.postalCode.length=6 -mosip.id.validation.identity.CNIENumber.length=30 -mosip.postal.code.length=6 -mosip.mobile.length=10 -mosip.email.length=50 -mosip.CINE.length=30 -mosip.kernel.prid.length=14 -preregistration.preid.regex=+[0-9] -auth.server.validate.url= -mosip.preregistration.booking.availability.sync.id=mosip.preregistration.booking.availability.sync -mosip.preregistration.booking.fetch.booking.id=mosip.preregistration.booking.fetch.booking -mosip.preregistration.booking.cancel.id=mosip.preregistration.booking.cancel -mosip.preregistration.booking.delete.id=mosip.preregistration.booking.delete -mosip.preregistration.booking.fetch.availability.id=mosip.preregistration.booking.fetch.availability -mosip.preregistration.booking.fetchPreidByDate.id=mosip.preregistration.booking.fetchPreidByDate -mosip.preregistration.booking.availability.increase.id=mosip.preregistration.booking.availability.increase -mosip.preregistration.booking.availability.check.id=mosip.preregistration.booking.availability.check -mosip.preregistration.booking.delete.old.id=mosip.preregistration.booking.delete.old -mosip.preregistration.booking.exception.id=mosip.preregistration.booking.parse.exception -mosip.kernel.idobjectvalidator.masterdata.documenttypes.rest.uri=https://api-internal.dev1.mosip.net/v1/masterdata/documenttypes/{documentcategorycode}/{langcode} -mosip.kernel.masterdata.validdoc.rest.uri==https://api-internal.dev1.mosip.net/masterdata/validdocuments/ - -mosip.preregistration.booking.id.book=mosip.preregistration.booking.book -# Name node url for HDFS -mosip.kernel.fsadapter.hdfs.name-node-url=hdfs://104.211.240.243:51000 - -# Key Distribution Center domain for Kerberos -mosip.kernel.fsadapter.hdfs.kdc-domain=NODE-MASTER.SOUTHINDIA.CLOUDAPP.AZURE.COM - -# Username to access hdfs. Change this to application username (regprocessor,prereg or idrepo) -mosip.kernel.fsadapter.hdfs.user-name=prereg - -# Password for hdfs user -mosip.kernel.fsadapter.hdfs.user-pass=Mosip@dev123 - -# HDFS log level. Change this to debug to see hdfs logs -logging.level.org.apache.hadoop=warn - -mosip.kernel.prid.sequence-limit=3 - -# Number of digits in repeating block allowed in id. For example if limit is 2, -# then 4xxx4 is allowed but 48xxx48 is not allowed in id (x is any digit) -#to disable validation assign zero or negative value -mosip.kernel.prid.repeating-block-limit=3 - - -# Lower bound of number of digits allowed in between two repeating digits in -# id. For example if limit is 2, then 11 and 1x1 is not allowed in id (x is any digit) to disable validation assign zero or negative value -mosip.kernel.prid.repeating-limit=2 - -# list of number that id should not be start with to disable null -mosip.kernel.prid.not-start-with=0,1 - -#restricted numbers for prid -mosip.kernel.prid.restricted-numbers=786,666 - -mosip.kernel.virus-scanner.host=104.211.200.46 -mosip.kernel.virus-scanner.port=3310 -mosip.batch.token.authmanager.url= https://api-internal.dev1.mosip.net/v1/authmanager/authenticate/useridPwd -mosip.batch.token.authmanager.appId=ida -mosip.batch.token.authmanager.userName=110005 -mosip.batch.token.authmanager.password=mosip -mosip.batch.token.request.id=mosip.io.doc.id -version=1.0 -auth-token-generator.rest.issuerUrl=http://dummyurl -mosip.notification.timezone: GMT+05:30 -preregistration.crypto.referenceId=INDIVIDUAL -preregistration.crypto.PrependThumbprint=false -preregistration.crypto.applicationId=PRE_REGISTRATION -prereg.auth.jwt.secret=Yn2kjibddFAWtnPJ2AFlL8WXmohJMCvigQggaEypa5E= -mosip.mandatory-languages=ara,eng -mosip.optional-languages=fra - -#the custom auth provider component names list -mosip.security.authentication.provider.beans.list=customJWTAuthProvider - - -mosip.kernel.auth.appids.realm.map={prereg:'preregistration',ida:'mosip',registrationclient:'mosip',regproc:'mosip',partner:'mosip',resident:'mosip',admin:'mosip',crereq:'mosip',creser:'mosip',datsha:'mosip'} -# To generate token from keycloak. Use by kernel auth adapter. -mosip.iam.adapter.clientid=mosip-prereg-client -mosip.iam.adapter.clientsecret= -mosip.iam.adapter.appid=prereg -# URL to get new Auth Token from OIDC provider & to do online validation of auth token with OIDC provider. -# auth.server.admin.issuer.uri=https://api-internal.dev1.mosip.net/keycloak/auth/realms/ -auth.server.admin.issuer.uri=https://iam.dev1.mosip.net/auth/realms/ - -spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER \ No newline at end of file diff --git a/pre-registration-booking-service/src/test/resources/booking.json b/pre-registration-booking-service/src/test/resources/booking.json deleted file mode 100644 index 04f45b77d64..00000000000 --- a/pre-registration-booking-service/src/test/resources/booking.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "id":"mosip.pre-registration.booking.book", - "ver":"1.0", - "reqTime":"2018-12-06T07:22:57.086+0000", - "request":{ - "registration_center_id":"1", - "reg_date":"2018-12-04", - "time-slot-from":"09:00", - "time-slot-to":"09:13" - } -} \ No newline at end of file diff --git a/pre-registration-booking-service/src/test/resources/bootstrap.properties b/pre-registration-booking-service/src/test/resources/bootstrap.properties deleted file mode 100644 index 29cdedc6f0a..00000000000 --- a/pre-registration-booking-service/src/test/resources/bootstrap.properties +++ /dev/null @@ -1,23 +0,0 @@ -spring.cloud.config.uri=localhost -spring.cloud.config.label=master -spring.cloud.config.name=pre-registration -spring.application.name=pre-registration-booking-service -spring.profiles.active=test -management.endpoints.web.exposure.include=refresh -spring.info.git.location=classpath:service-git.properties - -server.servlet.context-path=/preregistration/v1 -server.port=9095 - -openapi.info.title=Pre-Registration-Booking -openapi.info.description=Pre-Registration-Booking Service -openapi.info.version=1.0 -openapi.info.license.name=Mosip -openapi.info.license.url=https://docs.mosip.io/platform/license -openapi.service.servers[0].url=${server.servlet.context-path} -openapi.service.servers[0].description=Pre-Registration-Booking Service -openapi.group.name=${openapi.info.title} -openapi.group.paths[0]=/** - -preregistration.config.identityjson= -preregistration.identity= diff --git a/pre-registration-booking-service/src/test/resources/cancelAppointment.json b/pre-registration-booking-service/src/test/resources/cancelAppointment.json deleted file mode 100644 index b96d8570730..00000000000 --- a/pre-registration-booking-service/src/test/resources/cancelAppointment.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "id": "mosip.pre-registration.booking.book", - "ver" : "1.0", - "reqTime" : "2018-10-17T07:22:57.086+0000", - "request" : - { - "pre_registration_id":"23587986034785", - "registration_center_id":"1", - "reg_date":"2018-12-17", - "time-slot-from":"09:00", - "time-slot-to":"09:13" - } -} \ No newline at end of file diff --git a/pre-registration-booking-service/src/test/resources/create-schema.sql b/pre-registration-booking-service/src/test/resources/create-schema.sql deleted file mode 100644 index c76cd6a59b8..00000000000 --- a/pre-registration-booking-service/src/test/resources/create-schema.sql +++ /dev/null @@ -1 +0,0 @@ -CREATE SCHEMA IF NOT EXISTS PREREG; diff --git a/pre-registration-booking-service/src/test/resources/multibooking.json b/pre-registration-booking-service/src/test/resources/multibooking.json deleted file mode 100644 index e4c6c504344..00000000000 --- a/pre-registration-booking-service/src/test/resources/multibooking.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "id": "mosip.pre-registration.booking.book", - "version": "1.0", - "requesttime": "2019-05-09T15:31:32.957Z", - "request": { - "bookingRequest": [ - { - "preRegistrationId": "57239185716725", - "registration_center_id": "10001", - "appointment_date": "2019-05-09", - "time_slot_from": "14:45:00", - "time_slot_to": "15:00:00" - } - ] - } -} \ No newline at end of file From f827cc747c81020692aff02061df72cc3a6efd4c Mon Sep 17 00:00:00 2001 From: JanardhanBS-SyncByte Date: Wed, 4 Nov 2026 18:53:26 +0530 Subject: [PATCH 2/2] [issue-1633] moved pre-registration-booking-service to pre-registration repo for consolidation Signed-off-by: JanardhanBS-SyncByte --- .github/AGENTS.md | 2 +- README.md | 6 +++--- helm/AGENTS.md | 2 +- helm/prereg-booking/README.md | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/AGENTS.md b/.github/AGENTS.md index 1b8a7caa244..2ffe6d8c047 100644 --- a/.github/AGENTS.md +++ b/.github/AGENTS.md @@ -12,4 +12,4 @@ Do not glob. Never read `keys/`. └── keys/ # GPG — never read/edit/commit ``` -`push-trigger.yml`: Maven at aggregator (`kernel/`, `registration-processor/`). Docker = child paths. OSSRH skip `master`+PR. Regproc Docker artifact `registration-processor`. Booking service is not in this repo (mosip/pre-registration). +`push-trigger.yml`: Maven at aggregator (`kernel/`, `registration-processor/`). Docker = child paths. OSSRH skip `master`+PR. Regproc Docker artifact `registration-processor`. Booking service is moved to mosip/pre-registration. diff --git a/README.md b/README.md index 782fb3b06a2..e88771edfaf 100644 --- a/README.md +++ b/README.md @@ -34,9 +34,9 @@ This repository is the reference for how a country can adapt MOSIP: | Kernel SPIs | ID-object validator, MSG91 SMS, ClamAV virus scanner (`META-INF/spring.factories`) | | Registration processor | External stage (Vert.x) + External Integration Service stub REST | | Identity | Keycloak login theme (FTL) | -| Deploy | Helm chart for booking (`helm/prereg-booking`; service is not in this repo) | +| Deploy | Helm chart for booking (`helm/prereg-booking`; service is moved to mosip/pre-registration) | -Angular UIs (`pre-registration-ui`, `admin-ui`) live in their own MOSIP repositories, not this tree. Booking REST (`pre-registration-booking-service`) also lives elsewhere — see [Moved: pre-registration-booking-service](#moved-pre-registration-booking-service). Coverage is produced at build time (`mvn clean verify` → `target/site/jacoco/index.html`); TestNG report archives are not checked in. +Angular UIs (`pre-registration-ui`, `admin-ui`) live in their own MOSIP repositories, not this tree. Booking REST (`pre-registration-booking-service`) is moved — see [Moved: pre-registration-booking-service](#moved-pre-registration-booking-service). Coverage is produced at build time (`mvn clean verify` → `target/site/jacoco/index.html`); TestNG report archives are not checked in.