diff --git a/.classpath b/.classpath index c6d54598..d91be04b 100644 --- a/.classpath +++ b/.classpath @@ -29,15 +29,6 @@ - - - - - - - - - @@ -48,6 +39,18 @@ + + + + + + + + + + + + diff --git a/.gitignore b/.gitignore index b83d2226..c2187eec 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,7 @@ /target/ +target/classes/ +.classpath +/communityHallDocuments/ +target/classes/application-dev.properties +target/classes/application-prod.properties + diff --git a/jwtToken.txt b/jwtToken.txt index 4f50d0f6..7324af95 100644 --- a/jwtToken.txt +++ b/jwtToken.txt @@ -1 +1 @@ -eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyVHlwZSI6ImFkbWluIiwiaGFsbElkIjoxLCJtb2JpbGVOdW1iZXIiOjgzNDQ5NzkyOTIsImVtcGxveWVlSWQiOiIxIiwiem9uZSI6IjAwIiwiZXhwIjoxNzYyODYwNzk0fQ.ltHuRFZWZqHUvUki5jbMcGTDbU2JyOWU5cgMFbVrp_8KMag9HVtHQ9iSFGUyIMUe_T08b58_BG9ZtrtM8rHo9Q \ No newline at end of file +eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyVHlwZSI6ImFkbWluIiwiaGFsbElkIjoxLCJtb2JpbGVOdW1iZXIiOjgzNDQ5NzkyOTIsImVtcGxveWVlSWQiOiIxIiwiem9uZSI6IjAwIiwiZXhwIjoxNzczMTIyNTkxfQ.6cTw68Q9NsMgdKLtP7D1k0I_6PJQ62mFIOItwtpYz7o7FNC_Kf0qRzulFguzgnPpdvSwXF2v2w_PqIXte7eIMg \ No newline at end of file diff --git a/src/main/java/com/gcc/communityHall/controller/AdminAPIController.java b/src/main/java/com/gcc/communityHall/controller/AdminAPIController.java index 28f68d7c..02c703a8 100644 --- a/src/main/java/com/gcc/communityHall/controller/AdminAPIController.java +++ b/src/main/java/com/gcc/communityHall/controller/AdminAPIController.java @@ -71,6 +71,7 @@ import com.gcc.communityHall.repository.DiscountRangeRepository; import com.gcc.communityHall.repository.GccBlockingDateRepository; import com.gcc.communityHall.repository.GccBlockingHistoryRepository; import com.gcc.communityHall.repository.HallDetailsRepository; +import com.gcc.communityHall.repository.HallReasonRestrictionRepository; import com.gcc.communityHall.repository.HallImagesRepository; import com.gcc.communityHall.repository.NotificationRepository; import com.gcc.communityHall.repository.ReasonMasterRepository; @@ -97,10 +98,7 @@ import lombok.AllArgsConstructor; //@RestController //@RequestMapping("/admin/api") -@Tag( - name = "CRUD REST APIs for Admin in CommunityHall", - description = "CRUD REST APIs in CommunityHall to CREATE, UPDATE, FETCH AND DELETE Booking details" -) +@Tag(name = "CRUD REST APIs for Admin in CommunityHall", description = "CRUD REST APIs in CommunityHall to CREATE, UPDATE, FETCH AND DELETE Booking details") @RestController @RequestMapping("/communityhall/admin/api") @AllArgsConstructor @@ -168,32 +166,13 @@ public class AdminAPIController { @Autowired private ApplicationLogsRepository applicationLogsRepository; - @Operation( - summary = "Update HallDetails REST API", - description = "REST API to update the Hall Details" - ) + @Autowired + private HallReasonRestrictionRepository hallReasonRestrictionRepository; + + @Operation(summary = "Update HallDetails REST API", description = "REST API to update the Hall Details") @ApiResponses({ - @ApiResponse( - responseCode = "200", - description = "HTTP Status UPDATED", - content = @Content( - mediaType = "text/plain", - schema = @Schema(implementation = HallDetails.class), - examples = @ExampleObject(value = "Hall details updated successfully") - ) - ), - @ApiResponse( - responseCode = "500", - description = "HTTP Status Internal Server Error", - content = @Content( - mediaType = "application/json", - schema = @Schema(implementation = ErrorResponseDto.class), - examples = @ExampleObject( - name = "Internal Server Error Example", - value = "{ \"path\": \"/updateHallDetails\", \"status\": 500, \"error\": \"Internal Server Error\", \"timestamp\": \"2024-06-22T05:47:04.347+00:00\" }" - ) - ) - ) + @ApiResponse(responseCode = "200", description = "HTTP Status UPDATED", content = @Content(mediaType = "text/plain", schema = @Schema(implementation = HallDetails.class), examples = @ExampleObject(value = "Hall details updated successfully"))), + @ApiResponse(responseCode = "500", description = "HTTP Status Internal Server Error", content = @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponseDto.class), examples = @ExampleObject(name = "Internal Server Error Example", value = "{ \"path\": \"/updateHallDetails\", \"status\": 500, \"error\": \"Internal Server Error\", \"timestamp\": \"2024-06-22T05:47:04.347+00:00\" }"))) }) @PostMapping("/updateHallDetails") public ResponseEntity updateHallInfo( @@ -270,43 +249,18 @@ public class AdminAPIController { return ResponseEntity.ok("Success"); } - - @Operation( - summary = "Update Settlement Status REST API", - description = "REST API to update the Settlement Status to INITIATED" - ) + @Operation(summary = "Update Settlement Status REST API", description = "REST API to update the Settlement Status to INITIATED") @ApiResponses({ - @ApiResponse( - responseCode = "200", - description = "HTTP Status UPDATED", - content = @Content( - mediaType = "application/json", - schema = @Schema(implementation = Settlement.class), - examples = @ExampleObject( - name = "Settlement Example", - value = "{\"settlementId\": Id, \"Refundstatus\": \"INITIATED\", \"comments\": \"Settlement initiated successfully\"}" - ) - ) - ), - @ApiResponse( - responseCode = "500", - description = "HTTP Status Internal Server Error", - content = @Content( - mediaType = "application/json", - schema = @Schema(implementation = ErrorResponseDto.class), - examples = @ExampleObject( - name = "Internal Server Error Example", - value = "{ \"path\": \"/updateInitiatedSettlementStatus/{settlementId}\", \"status\": 500, \"error\": \"Internal Server Error\", \"timestamp\": \"2024-06-22T05:47:04.347+00:00\" }" - ) - ) - ) + @ApiResponse(responseCode = "200", description = "HTTP Status UPDATED", content = @Content(mediaType = "application/json", schema = @Schema(implementation = Settlement.class), examples = @ExampleObject(name = "Settlement Example", value = "{\"settlementId\": Id, \"Refundstatus\": \"INITIATED\", \"comments\": \"Settlement initiated successfully\"}"))), + @ApiResponse(responseCode = "500", description = "HTTP Status Internal Server Error", content = @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponseDto.class), examples = @ExampleObject(name = "Internal Server Error Example", value = "{ \"path\": \"/updateInitiatedSettlementStatus/{settlementId}\", \"status\": 500, \"error\": \"Internal Server Error\", \"timestamp\": \"2024-06-22T05:47:04.347+00:00\" }"))) }) @PostMapping("/updateInitiatedSettlementStatus/{settlementId}") public ResponseEntity updateInitiatedSettlementStatus( @PathVariable("settlementId") int settlementId, @RequestParam("status") BookingDetails.RefundStatus status, @RequestParam("comments") String comments) { - Settlement updateInitialiseSettlement = settlementService.updateSettlementStatus(settlementId, status, comments); + Settlement updateInitialiseSettlement = settlementService.updateSettlementStatus(settlementId, status, + comments); String adminname = (String) session.getAttribute("usertype"); Integer loginid = (Integer) session.getAttribute("id"); ApplicationLogs logs = new ApplicationLogs(); @@ -330,27 +284,11 @@ public class AdminAPIController { } } - @Operation( - summary = "HallDetails by HallId REST API", - description = "REST API to Retrieving the Hall Details by hallId" - ) + @Operation(summary = "HallDetails by HallId REST API", description = "REST API to Retrieving the Hall Details by hallId") @ApiResponses({ - @ApiResponse( - responseCode = "200", - description = "HTTP Status OK", - content = @Content( - mediaType = "application/json", - schema = @Schema(implementation = HallDetails.class) - ) - ), - @ApiResponse( - responseCode = "400", - description = "Bad Request" - ), - @ApiResponse( - responseCode = "404", - description = "Not Found" - ) + @ApiResponse(responseCode = "200", description = "HTTP Status OK", content = @Content(mediaType = "application/json", schema = @Schema(implementation = HallDetails.class))), + @ApiResponse(responseCode = "400", description = "Bad Request"), + @ApiResponse(responseCode = "404", description = "Not Found") }) @GetMapping("/getHallDetails/{hallId}") public ResponseEntity getHallDetails(@PathVariable String hallId) { @@ -362,7 +300,7 @@ public class AdminAPIController { } HallDetails hallDetails = hallDetailsRepository.findHallDetailsById(id); - //System.out.println(hallDetails.isActive()); + // System.out.println(hallDetails.isActive()); if (hallDetails != null) { return ResponseEntity.ok(hallDetails); } else { @@ -370,10 +308,7 @@ public class AdminAPIController { } } - @Operation( - summary = "Saving the DiscountRange REST API", - description = "REST API to Saving the Discount Range for usertypes" - ) + @Operation(summary = "Saving the DiscountRange REST API", description = "REST API to Saving the Discount Range for usertypes") @PostMapping("/savediscountrange") public String saveDiscountrange( @RequestParam String userType, @@ -427,12 +362,10 @@ public class AdminAPIController { return "success"; } - @Operation( - summary = " Update the DiscountRange REST API", - description = "REST API to Updating the Discount Range for usertypes" - ) + @Operation(summary = " Update the DiscountRange REST API", description = "REST API to Updating the Discount Range for usertypes") @PutMapping("/updateById/{id}") - public String updateDiscountRangeById(@PathVariable int id, @RequestParam float discountRange, HttpSession session) { + public String updateDiscountRangeById(@PathVariable int id, @RequestParam float discountRange, + HttpSession session) { String adminname = (String) session.getAttribute("usertype"); Optional existingDiscount = discountRangeRepo.findById(id); if (existingDiscount.isPresent()) { @@ -462,11 +395,7 @@ public class AdminAPIController { } } - - @Operation( - summary = " Delete the DiscountRange REST API", - description = "REST API to Deleting the Discount for usertypes" - ) + @Operation(summary = " Delete the DiscountRange REST API", description = "REST API to Deleting the Discount for usertypes") @DeleteMapping("/deleteById/{id}") public ResponseEntity deleteDiscountRangeById(@PathVariable int id) { if (discountRangeRepo.existsById(id)) { @@ -523,70 +452,77 @@ public class AdminAPIController { } - @Operation( - summary = "Retrieving the Discount Details REST API", - description = "REST API to Retrieve the Discount Details for usertypes" - ) - //Retrieving the Discount Details + @Operation(summary = "Retrieving the Discount Details REST API", description = "REST API to Retrieve the Discount Details for usertypes") + // Retrieving the Discount Details @GetMapping("/getDiscountDetails") public Optional getDIscountDetails(@RequestParam("id") int id) { Optional discountdetails = discountRangeRepo.findById(id); return discountdetails; } - @Operation( - summary = "Save Reasons REST API", - description = "REST API to save the reasons" - ) - //saving the Reason + @Operation(summary = "Save Reasons REST API", description = "REST API to save the reasons") + // saving the Reason @PostMapping("/saveReason") public ResponseEntity saveReason(@RequestBody ReasonMaster reasaon) { return ResponseEntity.ok(reasonMasterService.saveTheReason(reasaon)); } - @Operation( - summary = "All Reasons REST API", - description = "REST API to retrie the allreasons" - ) - //retrieving the allreasons + @Operation(summary = "All Reasons REST API", description = "REST API to retrie the allreasons") + // retrieving the allreasons @GetMapping("/getReasons") @ResponseBody public List getAllReasons() { return reasonMasterService.getAllReasons(); } - @Operation( - summary = "Reason Documents by reasonId REST API", - description = "REST API to Get the ReasonDocuments By reasonId" - ) - //Getting ReasonDocuments By reasonId + // retrieving allowed reasons for a specific hall (filtered by restriction) + @GetMapping("/getAllowedReasons") + @ResponseBody + public List getAllowedReasons(@RequestParam int hallId) { + HallDetails hallDetails = hallDetailsRepository.findHallDetailsById(hallId); + if (hallDetails != null && hallDetails.isReasonRestricted()) { + List allowedReasonIds = hallReasonRestrictionRepository.findReasonIdsByHallId(hallId); + if (!allowedReasonIds.isEmpty()) { + List allReasons = reasonMasterService.getAllReasons(); + return allReasons.stream() + .filter(r -> allowedReasonIds.contains(r.getReasonId())) + .collect(java.util.stream.Collectors.toList()); + } + } + return reasonMasterService.getAllReasons(); + } + + @Operation(summary = "Reason Documents by reasonId REST API", description = "REST API to Get the ReasonDocuments By reasonId") + // Getting ReasonDocuments By reasonId @GetMapping("/getReasonDocumentDetails") public List getReasonDocumentDetails(@RequestParam int reasonId) { return reasonMasterService.getReasonDocumentDetailsByReasonId(reasonId); } - @Operation( - summary = "Booking Details by Fromdate,toDate and HallId REST API", - description = "REST API to get the Booking Details by Fromdate,toDate and HallId for GccBlokcing" - ) -// @GetMapping("/filter") -// public ResponseEntity> getFilteredBookings( -// @RequestParam("fromDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate fromDate, -// @RequestParam("toDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate toDate, -// @RequestParam("hallIds") List hallIds) { -// -// List bookings = bookingService.getFilteredBookings(fromDate, toDate, hallIds); -// -// List responses = new ArrayList<>(); -// for (BookingDetails bookingDetails : bookings) { -// // Fetch GccBlockingDate records for each bookingId -// List gccBlockedList = blockingDateRepository.getByBookingId(bookingDetails.getBookingId()); -// Integer blockingId = gccBlockedList.isEmpty() ? null : gccBlockedList.get(0).getBlockingId(); -// responses.add(new BookingResponseDTO(bookingDetails, blockingId)); -// } -// -// return ResponseEntity.ok(responses); -// } + @Operation(summary = "Booking Details by Fromdate,toDate and HallId REST API", description = "REST API to get the Booking Details by Fromdate,toDate and HallId for GccBlokcing") + // @GetMapping("/filter") + // public ResponseEntity> getFilteredBookings( + // @RequestParam("fromDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate + // fromDate, + // @RequestParam("toDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate + // toDate, + // @RequestParam("hallIds") List hallIds) { + // + // List bookings = bookingService.getFilteredBookings(fromDate, + // toDate, hallIds); + // + // List responses = new ArrayList<>(); + // for (BookingDetails bookingDetails : bookings) { + // // Fetch GccBlockingDate records for each bookingId + // List gccBlockedList = + // blockingDateRepository.getByBookingId(bookingDetails.getBookingId()); + // Integer blockingId = gccBlockedList.isEmpty() ? null : + // gccBlockedList.get(0).getBlockingId(); + // responses.add(new BookingResponseDTO(bookingDetails, blockingId)); + // } + // + // return ResponseEntity.ok(responses); + // } @GetMapping("/filter") public ResponseEntity> getFilteredBookings( @RequestParam("fromDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate fromDate, @@ -594,7 +530,8 @@ public class AdminAPIController { @RequestParam("hallIds") List hallIds) { List bookings = bookingService.getFilteredBookings(fromDate, toDate, hallIds); - List gccBlockedList = blockingDateRepository.findByFromDateAndToDateBetweenAndHallIdIn(fromDate, toDate, hallIds); + List gccBlockedList = blockingDateRepository + .findByFromDateAndToDateBetweenAndHallIdIn(fromDate, toDate, hallIds); Map response = new HashMap<>(); response.put("bookings", bookings); @@ -603,22 +540,19 @@ public class AdminAPIController { return ResponseEntity.ok(response); } - - @Operation( - summary = " GCC Blocked Booking Details REST API", - description = "REST API to get the GCC Blocked BookingDetails" - ) - //retrieving the GCC Blocked BookingDetails + @Operation(summary = " GCC Blocked Booking Details REST API", description = "REST API to get the GCC Blocked BookingDetails") + // retrieving the GCC Blocked BookingDetails @GetMapping("/blockedevents") public ResponseEntity> getBlockedEvents( @RequestParam("fromDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate fromDate, @RequestParam("toDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate toDate, - @RequestParam("hallIds") List hallIds - ) { - //System.out.println("Blocked Events Request - fromDate: " + fromDate + ", toDate: " + toDate + ", hallIds: " + hallIds ); + @RequestParam("hallIds") List hallIds) { + // System.out.println("Blocked Events Request - fromDate: " + fromDate + ", + // toDate: " + toDate + ", hallIds: " + hallIds ); List blockedBookings = bookingService.getBlockedEvents(fromDate, toDate, hallIds); - // List bookingDetails = bookingService.getByBookingId(fromDate,toDate,hallIds,blockingId,bookingId); + // List bookingDetails = + // bookingService.getByBookingId(fromDate,toDate,hallIds,blockingId,bookingId); if (blockedBookings.isEmpty()) { // System.out.println("No blocked bookings found."); @@ -632,15 +566,11 @@ public class AdminAPIController { return ResponseEntity.ok(blockedBookings); } - - @Operation( - summary = "UNBLOCK the gcc Blocked Event REST API", - description = "REST API to unblocking the Gcc blocked Events for blocking" - ) + @Operation(summary = "UNBLOCK the gcc Blocked Event REST API", description = "REST API to unblocking the Gcc blocked Events for blocking") @GetMapping("/cancelByid") public ResponseEntity cancellationById(@RequestParam int blockingId, - @RequestParam("fromDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate fromDate, - @RequestParam("endDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) { + @RequestParam("fromDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate fromDate, + @RequestParam("endDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) { // Fetch the blocking date entity GccBlockingDate blockingDate = blockingDateRepository.findById(blockingId).orElse(null); @@ -668,7 +598,8 @@ public class AdminAPIController { List bookingCalendars = bookingService.getBookedslots(fromDate, endDate, hallIdList); if (bookingCalendars.isEmpty()) { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("No booking slots found for the given date range and hall IDs."); + return ResponseEntity.status(HttpStatus.NOT_FOUND) + .body("No booking slots found for the given date range and hall IDs."); } // Iterate over bookingCalendars and update them as needed @@ -712,118 +643,120 @@ public class AdminAPIController { applicationLogsRepository.save(logs); return ResponseEntity.ok("Success"); } -// @GetMapping("/cancelByid") -// public ResponseEntity cancellationById( -// @RequestParam int blockingId, -// @RequestParam int bookingId, -// @RequestParam("fromDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate fromDate, -// @RequestParam("endDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate, -// @RequestParam(value = "hallId", required = false) List hallId) { -// -// System.out.println("Received blockingId: " + blockingId); -// System.out.println("Received bookingId: " + bookingId); -// System.out.println("Received fromDate: " + fromDate); -// System.out.println("Received hallId: " + hallId); -// -// // Retrieve blocking date -// GccBlockingDate blockingDate = blockingDateRepository.findById(blockingId).orElse(null); -// -// if (blockingDate == null) { -// return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Blocking ID not found."); -// } -// -// if (hallId != null && bookingId > 0) { -// // Specific bookingId and hallId selected -// -// // Retrieve and update booking calendar -// List bookingCalendar = bookingService.getBookedslots(fromDate, endDate, hallId); -// if (bookingCalendar.isEmpty()) { -// return ResponseEntity.status(HttpStatus.NOT_FOUND).body("No booking slots found for the given date and hall ID."); -// } -// -// BookingCalendar bookingSlots = bookingCalendar.get(0); -// bookingSlots.setBookingId_1(null); -// bookingSlots.setBookingId_2(null); -// bookingSlots.setMorningSlot(false); -// bookingSlots.setEveningSlot(false); -// -// // Process hallIds and bookingIds -// List hallIdList = Arrays.asList(blockingDate.getHallId().split(",")); -// hallIdList.remove(hallId.toString()); -// String updatedHallIds = String.join(",", hallIdList); -// -// List bookingIdList = Arrays.asList(blockingDate.getBookingIds().split(",")); -// bookingIdList.remove(Integer.toString(bookingId)); -// String updatedBookingIds = String.join(",", bookingIdList); -// -// // Update blockingDate with new values -// blockingDate.setHallId(updatedHallIds); -// blockingDate.setBookingIds(updatedBookingIds); -// -// // Create an entry in GccBlockingHistory -// GccBlockingHistory blockingHistory = new GccBlockingHistory(); -// blockingHistory.setBlockedStatus(GccBlockingHistory.BlockedStatus.UNBLOCKED); -// blockingHistory.setBlockingReason(blockingHistory.getBlockingReason()); -// blockingHistory.setCdate(new Date()); -// blockingHistory.setStartDate(blockingHistory.getStartDate()); -// blockingHistory.setEndDate(blockingHistory.getEndDate()); -// blockingHistory.setUpdatedBy(blockingHistory.getUpdatedBy()); -// blockingHistory.setBookingIds(updatedBookingIds); -// blockingHistory.setHallId(updatedHallIds); -// blockingHistoryRepository.save(blockingHistory); -// -// // Update the blocking date status -// blockingDate.setBlockedStatus(GccBlockingDate.BlockedStatus.UNBLOCKED); -// blockingDateRepository.save(blockingDate); -// -// // Save booking calendar updates -// bookingCalendarRepository.save(bookingSlots); -// -// } else { -// // All halls and bookings selected -// // Retrieve and clear all bookings for the date range -// List bookingCalendars = bookingService.getBookedslots(fromDate,endDate,hallId); -// for (BookingCalendar bookingCalendar : bookingCalendars) { -// bookingCalendar.setBookingId_1(null); -// bookingCalendar.setBookingId_2(null); -// bookingCalendar.setMorningSlot(false); -// bookingCalendar.setEveningSlot(false); -// bookingCalendarRepository.save(bookingCalendar); -// } -// -// // Update blocking date status to UNBLOCKED -// blockingDate.setBlockedStatus(GccBlockingDate.BlockedStatus.UNBLOCKED); -// blockingDateRepository.save(blockingDate); -// -// // Create an entry in GccBlockingHistory -// GccBlockingHistory blockingHistory = new GccBlockingHistory(); -// blockingHistory.setBlockedStatus(GccBlockingHistory.BlockedStatus.UNBLOCKED); -// blockingHistory.setBlockingReason(blockingHistory.getBlockingReason()); -// blockingHistory.setCdate(new Date()); -// blockingHistory.setStartDate(blockingHistory.getStartDate()); -// blockingHistory.setEndDate(blockingHistory.getEndDate()); -// blockingHistory.setUpdatedBy(blockingHistory.getUpdatedBy()); -// blockingHistoryRepository.save(blockingHistory); -// } -// -// return ResponseEntity.ok("Success"); -// } - - @Operation( - summary = "HAll IMAGES by HallId REST API", - description = "REST API to get the hall Images by Hall Id" - ) - //retrieving Hall Images by Hallid + // @GetMapping("/cancelByid") + // public ResponseEntity cancellationById( + // @RequestParam int blockingId, + // @RequestParam int bookingId, + // @RequestParam("fromDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate + // fromDate, + // @RequestParam("endDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate + // endDate, + // @RequestParam(value = "hallId", required = false) List hallId) { + // + // System.out.println("Received blockingId: " + blockingId); + // System.out.println("Received bookingId: " + bookingId); + // System.out.println("Received fromDate: " + fromDate); + // System.out.println("Received hallId: " + hallId); + // + // // Retrieve blocking date + // GccBlockingDate blockingDate = + // blockingDateRepository.findById(blockingId).orElse(null); + // + // if (blockingDate == null) { + // return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Blocking ID not + // found."); + // } + // + // if (hallId != null && bookingId > 0) { + // // Specific bookingId and hallId selected + // + // // Retrieve and update booking calendar + // List bookingCalendar = + // bookingService.getBookedslots(fromDate, endDate, hallId); + // if (bookingCalendar.isEmpty()) { + // return ResponseEntity.status(HttpStatus.NOT_FOUND).body("No booking slots + // found for the given date and hall ID."); + // } + // + // BookingCalendar bookingSlots = bookingCalendar.get(0); + // bookingSlots.setBookingId_1(null); + // bookingSlots.setBookingId_2(null); + // bookingSlots.setMorningSlot(false); + // bookingSlots.setEveningSlot(false); + // + // // Process hallIds and bookingIds + // List hallIdList = Arrays.asList(blockingDate.getHallId().split(",")); + // hallIdList.remove(hallId.toString()); + // String updatedHallIds = String.join(",", hallIdList); + // + // List bookingIdList = + // Arrays.asList(blockingDate.getBookingIds().split(",")); + // bookingIdList.remove(Integer.toString(bookingId)); + // String updatedBookingIds = String.join(",", bookingIdList); + // + // // Update blockingDate with new values + // blockingDate.setHallId(updatedHallIds); + // blockingDate.setBookingIds(updatedBookingIds); + // + // // Create an entry in GccBlockingHistory + // GccBlockingHistory blockingHistory = new GccBlockingHistory(); + // blockingHistory.setBlockedStatus(GccBlockingHistory.BlockedStatus.UNBLOCKED); + // blockingHistory.setBlockingReason(blockingHistory.getBlockingReason()); + // blockingHistory.setCdate(new Date()); + // blockingHistory.setStartDate(blockingHistory.getStartDate()); + // blockingHistory.setEndDate(blockingHistory.getEndDate()); + // blockingHistory.setUpdatedBy(blockingHistory.getUpdatedBy()); + // blockingHistory.setBookingIds(updatedBookingIds); + // blockingHistory.setHallId(updatedHallIds); + // blockingHistoryRepository.save(blockingHistory); + // + // // Update the blocking date status + // blockingDate.setBlockedStatus(GccBlockingDate.BlockedStatus.UNBLOCKED); + // blockingDateRepository.save(blockingDate); + // + // // Save booking calendar updates + // bookingCalendarRepository.save(bookingSlots); + // + // } else { + // // All halls and bookings selected + // // Retrieve and clear all bookings for the date range + // List bookingCalendars = + // bookingService.getBookedslots(fromDate,endDate,hallId); + // for (BookingCalendar bookingCalendar : bookingCalendars) { + // bookingCalendar.setBookingId_1(null); + // bookingCalendar.setBookingId_2(null); + // bookingCalendar.setMorningSlot(false); + // bookingCalendar.setEveningSlot(false); + // bookingCalendarRepository.save(bookingCalendar); + // } + // + // // Update blocking date status to UNBLOCKED + // blockingDate.setBlockedStatus(GccBlockingDate.BlockedStatus.UNBLOCKED); + // blockingDateRepository.save(blockingDate); + // + // // Create an entry in GccBlockingHistory + // GccBlockingHistory blockingHistory = new GccBlockingHistory(); + // blockingHistory.setBlockedStatus(GccBlockingHistory.BlockedStatus.UNBLOCKED); + // blockingHistory.setBlockingReason(blockingHistory.getBlockingReason()); + // blockingHistory.setCdate(new Date()); + // blockingHistory.setStartDate(blockingHistory.getStartDate()); + // blockingHistory.setEndDate(blockingHistory.getEndDate()); + // blockingHistory.setUpdatedBy(blockingHistory.getUpdatedBy()); + // blockingHistoryRepository.save(blockingHistory); + // } + // + // return ResponseEntity.ok("Success"); + // } + + @Operation(summary = "HAll IMAGES by HallId REST API", description = "REST API to get the hall Images by Hall Id") + // retrieving Hall Images by Hallid @GetMapping("/getImageById") public List getImageDetails(@RequestParam int hallId) { return hallService.getHallImages(hallId); } - @Operation( - summary = "GCC Blocking REST API", - description = "REST API to Block the Halls by Admin" - ) - //GccBlocking Api + @Operation(summary = "GCC Blocking REST API", description = "REST API to Block the Halls by Admin") + // GccBlocking Api @PostMapping("/cancelAll") public ResponseEntity cancelAllBookings( @RequestParam("fromDate") String fromDate, @@ -844,7 +777,8 @@ public class AdminAPIController { .collect(Collectors.toList()); // Call the service with descriptions and documents - bookingService.cancelAllBookings(fromDate, toDate, hallIdsList, reasonforblocking, selectedBookings, updatedBy, descriptions, documents); + bookingService.cancelAllBookings(fromDate, toDate, hallIdsList, reasonforblocking, selectedBookings, updatedBy, + descriptions, documents); String adminname = (String) session.getAttribute("usertype"); Integer loginid = (Integer) session.getAttribute("id"); ApplicationLogs logs = new ApplicationLogs(); @@ -864,35 +798,39 @@ public class AdminAPIController { return ResponseEntity.ok("Success"); } -// @PostMapping("/blockhall") -// public ResponseEntity blockHall( -// @RequestParam("blockingId") Integer blockingId, -// @RequestParam("hallID") String hallID, // Ensure this matches the parameter name used in AJAX -// @RequestParam(value = "selectedBookings", required = false) List selectedBookings, -// HttpSession session) { -// -// String updatedBy = (String) session.getAttribute("employeeId"); -// Optional gccblocking = blockingDateRepository.findById(blockingId); -// GccBlockingDate gccblockingdata = gccblocking.get(); -// -// // Convert startDate and endDate to String -// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); -// String startDateString = sdf.format(gccblockingdata.getStartDate()); -// String endDateString = sdf.format(gccblockingdata.getEndDate()); -// -// // Split and convert hall IDs -// List hallIdsList = Arrays.stream(hallID.split(",")) -// .map(Long::parseLong) -// .collect(Collectors.toList()); -// -// System.out.println("selected BookingIds: " + selectedBookings); -// -// // Pass the formatted date strings -// bookingService.cancelAllBookings(startDateString, endDateString, hallIdsList, gccblockingdata.getDepartment(), gccblockingdata.getBlockingReason(), selectedBookings, updatedBy); -// -// return ResponseEntity.ok("Success"); -// } - + // @PostMapping("/blockhall") + // public ResponseEntity blockHall( + // @RequestParam("blockingId") Integer blockingId, + // @RequestParam("hallID") String hallID, // Ensure this matches the parameter + // name used in AJAX + // @RequestParam(value = "selectedBookings", required = false) List + // selectedBookings, + // HttpSession session) { + // + // String updatedBy = (String) session.getAttribute("employeeId"); + // Optional gccblocking = + // blockingDateRepository.findById(blockingId); + // GccBlockingDate gccblockingdata = gccblocking.get(); + // + // // Convert startDate and endDate to String + // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + // String startDateString = sdf.format(gccblockingdata.getStartDate()); + // String endDateString = sdf.format(gccblockingdata.getEndDate()); + // + // // Split and convert hall IDs + // List hallIdsList = Arrays.stream(hallID.split(",")) + // .map(Long::parseLong) + // .collect(Collectors.toList()); + // + // System.out.println("selected BookingIds: " + selectedBookings); + // + // // Pass the formatted date strings + // bookingService.cancelAllBookings(startDateString, endDateString, hallIdsList, + // gccblockingdata.getDepartment(), gccblockingdata.getBlockingReason(), + // selectedBookings, updatedBy); + // + // return ResponseEntity.ok("Success"); + // } @GetMapping("/bookingdetailsByuserId") public List getuserDetails(@RequestParam Integer userId) { @@ -901,55 +839,64 @@ public class AdminAPIController { @GetMapping("/settlement-approved") public ResponseEntity> getApprovedSettlements(HttpSession session) { - List approvedSettlements = settlementRepository.findByBookingDetailsRefundStatus(RefundStatus.APPROVED); + List approvedSettlements = settlementRepository + .findByBookingDetailsRefundStatus(RefundStatus.APPROVED); return ResponseEntity.ok(approvedSettlements); } -// @PostMapping("/complete-refund") -// public ResponseEntity completeRefund(@RequestBody List bookingIds, HttpSession session, HttpServletResponse response) throws IOException { -// String token = (String) session.getAttribute("jwtToken"); -// //System.out.println("tokensssssssss" + token); -// -// // Validate JWT token -// if (token != null && jwtUtil.validateToken(token)) { -// // System.out.println("tokennnnnnnnnnnnnnns" + token); -// try { -// // System.out.println("Received booking IDs for refund: " + bookingIds); -// -// List bookids = bookingService.processRefundRequests(bookingIds); -// -// if (!bookids.isEmpty()) { -// // Prepare and return error response if there are errors -// StringBuilder errorResponse = new StringBuilder("Errors processing refund for IDs: "); -// for (String bookId : bookids) { -// errorResponse.append(bookId).append(", "); -// } -// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse.toString()); -// } -// -// return ResponseEntity.ok("Refund completed successfully"); -// } catch (Exception e) { -// e.printStackTrace(); -// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error processing refund: " + e.getMessage()); -// } -// } else { -// // Token is invalid or not present, redirect to login -// session.invalidate(); // Invalidate the session to clear all session attributes -// response.sendRedirect("/login"); // Redirect to the login page -// return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); // Return HTTP 401 Unauthorized -// } -// } - - // @GetMapping("/Gccblocking") -// public ResponseEntity> getGccBlockingEvents(@RequestParam("hallId") int hallId) { -// System.out.println("Received hallId: " + hallId); -// -// List results = bookingService.getGccBlockingEvents(hallId); -// -// return ResponseEntity.ok(results); -// } + // @PostMapping("/complete-refund") + // public ResponseEntity completeRefund(@RequestBody List + // bookingIds, HttpSession session, HttpServletResponse response) throws + // IOException { + // String token = (String) session.getAttribute("jwtToken"); + // //System.out.println("tokensssssssss" + token); + // + // // Validate JWT token + // if (token != null && jwtUtil.validateToken(token)) { + // // System.out.println("tokennnnnnnnnnnnnnns" + token); + // try { + // // System.out.println("Received booking IDs for refund: " + bookingIds); + // + // List bookids = bookingService.processRefundRequests(bookingIds); + // + // if (!bookids.isEmpty()) { + // // Prepare and return error response if there are errors + // StringBuilder errorResponse = new StringBuilder("Errors processing refund for + // IDs: "); + // for (String bookId : bookids) { + // errorResponse.append(bookId).append(", "); + // } + // return + // ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse.toString()); + // } + // + // return ResponseEntity.ok("Refund completed successfully"); + // } catch (Exception e) { + // e.printStackTrace(); + // return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error + // processing refund: " + e.getMessage()); + // } + // } else { + // // Token is invalid or not present, redirect to login + // session.invalidate(); // Invalidate the session to clear all session + // attributes + // response.sendRedirect("/login"); // Redirect to the login page + // return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); // Return HTTP + // 401 Unauthorized + // } + // } + + // @GetMapping("/Gccblocking") + // public ResponseEntity> + // getGccBlockingEvents(@RequestParam("hallId") int hallId) { + // System.out.println("Received hallId: " + hallId); + // + // List results = bookingService.getGccBlockingEvents(hallId); + // + // return ResponseEntity.ok(results); + // } @GetMapping("/Gccblocking") public ResponseEntity> getGccBlockingEvents(@RequestParam("hallId") String hallId) { - //System.out.println("Received hallId: " + hallId); + // System.out.println("Received hallId: " + hallId); List results = bookingService.getGccBlockingEvents(hallId); @@ -962,7 +909,7 @@ public class AdminAPIController { @RequestParam int blockingId) { // System.out.println("Received hallIds: " + hallIds); - //System.out.println("Received blockingId: " + blockingId); + // System.out.println("Received blockingId: " + blockingId); List hallIdList; try { @@ -987,13 +934,15 @@ public class AdminAPIController { for (int hallId : hallIdList) { int bookingCount = bookingDetailsRepository.countByHallIdAndBookingDateBetween(hallId, startDate, endDate); - //System.out.println("bookingCount==="+bookingCount); + // System.out.println("bookingCount==="+bookingCount); Optional hallDetailsOpt = hallDetailsRepository.findById(hallId); if (hallDetailsOpt.isPresent()) { HallDetails hallDetails = hallDetailsOpt.get(); - List bookingIds = bookingDetailsRepository.findBookingIdsByHallIdAndBookingDateBetween(hallId, startDate, endDate); - // System.out.println("Booking IDs for hallId " + hallId + ": " + bookingIds); // Add this line + List bookingIds = bookingDetailsRepository.findBookingIdsByHallIdAndBookingDateBetween(hallId, + startDate, endDate); + // System.out.println("Booking IDs for hallId " + hallId + ": " + bookingIds); + // // Add this line Map hallInfo = new HashMap<>(); hallInfo.put("hallName", hallDetails.getHallName()); @@ -1012,10 +961,10 @@ public class AdminAPIController { @GetMapping("/getbookingdetails") public ResponseEntity> getBookingDetails(@RequestParam("bookingId") Long bookingId) { - //System.out.println("Received bookingId: " + bookingId); + // System.out.println("Received bookingId: " + bookingId); try { List details = bookingService.findBookingDetailsByBookingId(bookingId); - //System.out.println("bookingdetails==="+details); + // System.out.println("bookingdetails==="+details); return ResponseEntity.ok(details); } catch (Exception e) { e.printStackTrace(); @@ -1023,7 +972,6 @@ public class AdminAPIController { } } - @GetMapping("/blockedHallsByHallIdAndReason") @ResponseBody public Map viewBlockedHallsByHallIdAndReason( @@ -1032,11 +980,13 @@ public class AdminAPIController { @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date startDate, @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date endDate) { - List blockedHalls = blockingDateRepository.findByBlockingReasonAndDateRange(blockingReason, startDate, endDate); + List blockedHalls = blockingDateRepository.findByBlockingReasonAndDateRange(blockingReason, + startDate, endDate); // Ensure distinct by hallId and other keys List uniqueGccBlockingDates = blockedHalls.stream() - .filter(distinctByKey(g -> Arrays.asList(g.getHallId(), g.getBlockingReason(), g.getStartDate(), g.getEndDate()))) + .filter(distinctByKey( + g -> Arrays.asList(g.getHallId(), g.getBlockingReason(), g.getStartDate(), g.getEndDate()))) .collect(Collectors.toList()); // Prepare response data @@ -1083,7 +1033,6 @@ public class AdminAPIController { return response; } - // Utility method to ensure distinct by a key private static Predicate distinctByKey(Function keyExtractor) { Set seen = new HashSet<>(); @@ -1092,7 +1041,8 @@ public class AdminAPIController { // Method to calculate number of bookings private int calculateBookings(HallDetails hall, GccBlockingDate blockedHall) { - return blockingDateRepository.countBlockedBookings(hall.getHallId(), blockedHall.getStartDate(), blockedHall.getEndDate()); + return blockingDateRepository.countBlockedBookings(hall.getHallId(), blockedHall.getStartDate(), + blockedHall.getEndDate()); } private double calculateRefund(HallDetails hall, GccBlockingDate blockedHall) { @@ -1100,7 +1050,7 @@ public class AdminAPIController { return 0.0; } - //admin dashboard + // admin dashboard @GetMapping("/bookingstatistics") public ResponseEntity>> getBookingStatistics( @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate fromDate, @@ -1111,7 +1061,8 @@ public class AdminAPIController { @RequestParam(required = false, defaultValue = "ALL") String userType) { try { - Map> statistics = bookingService.getBookingStatistics(fromDate, toDate, zone, division, hallid, userType); + Map> statistics = bookingService.getBookingStatistics(fromDate, toDate, zone, + division, hallid, userType); return ResponseEntity.ok(statistics); } catch (Exception e) { // Log the exception and return an appropriate error response @@ -1135,18 +1086,18 @@ public class AdminAPIController { @PostMapping("/savenewHallImages") public ResponseEntity updateHallImages(@RequestParam("hallId") Integer hallId, - @RequestParam("newHallImages") MultipartFile[] newHallImages) { + @RequestParam("newHallImages") MultipartFile[] newHallImages) { // Call the service method to update the hall images hallService.updatenewHallImages(hallId, newHallImages); return ResponseEntity.ok().build(); } -// @DeleteMapping("/deleteHallImage/{hallImageId}") -// public ResponseEntity deleteHallImage(@PathVariable Long hallImageId) { -// // Call the service method to delete the hall image -// hallService.deleteHallImage(hallImageId); -// return ResponseEntity.ok().build(); -// } + // @DeleteMapping("/deleteHallImage/{hallImageId}") + // public ResponseEntity deleteHallImage(@PathVariable Long hallImageId) { + // // Call the service method to delete the hall image + // hallService.deleteHallImage(hallImageId); + // return ResponseEntity.ok().build(); + // } @PutMapping("/updateHallImage/{hallImageId}") public ResponseEntity> updateHallImage( @@ -1161,7 +1112,8 @@ public class AdminAPIController { } catch (IllegalArgumentException e) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Collections.singletonMap("error", e.getMessage())); } catch (IOException e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Collections.singletonMap("error", "Failed to update image")); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body(Collections.singletonMap("error", "Failed to update image")); } } @@ -1223,7 +1175,7 @@ public class AdminAPIController { } } - //gccapps + // gccapps @GetMapping("/viewsettlement-pending") public ResponseEntity> viewSettlementPendingMaster(HttpSession session) { @@ -1239,7 +1191,6 @@ public class AdminAPIController { return ResponseEntity.ok(response); } - @GetMapping("/viewsettlement-complete") public ResponseEntity> viewSettlementcompleteMaster(HttpSession session) { @@ -1342,10 +1293,16 @@ public class AdminAPIController { List userList = handleUserRequest(request, fromDate, toDate, userstatus, usertype); List bookingList = handleBookingRequest(request, fromDate, toDate, bookingStatus, bookingId); - List bookingSettlementList = handleBookingSettlementRequest(request, fromDate, toDate, refundStatus); - List paymentList = request.equals("3") ? bookingService.getAllPaymentsDetails(fromDate, toDate) : new ArrayList<>(); - List userbookingList = request.equals("4") ? bookingService.getBookingUserDetailsReport(fromDate, toDate) : new ArrayList<>(); - List hallbookingList = request.equals("5") ? bookingService.getBookingHallDetailsReport(fromDate, toDate) : new ArrayList<>(); + List bookingSettlementList = handleBookingSettlementRequest(request, fromDate, toDate, + refundStatus); + List paymentList = request.equals("3") ? bookingService.getAllPaymentsDetails(fromDate, toDate) + : new ArrayList<>(); + List userbookingList = request.equals("4") + ? bookingService.getBookingUserDetailsReport(fromDate, toDate) + : new ArrayList<>(); + List hallbookingList = request.equals("5") + ? bookingService.getBookingHallDetailsReport(fromDate, toDate) + : new ArrayList<>(); response.put("users", userList); response.put("bookings", bookingList); @@ -1365,7 +1322,8 @@ public class AdminAPIController { return new ResponseEntity<>(response, HttpStatus.OK); } - private List handleUserRequest(String request, String fromDate, String toDate, String userstatus, String usertype) { + private List handleUserRequest(String request, String fromDate, String toDate, String userstatus, + String usertype) { if (!request.equals("1")) { return new ArrayList<>(); } @@ -1381,7 +1339,8 @@ public class AdminAPIController { return userService.getAllUsers(fromDate, toDate); } - private List handleBookingRequest(String request, String fromDate, String toDate, String bookingStatus, Long bookingId) { + private List handleBookingRequest(String request, String fromDate, String toDate, String bookingStatus, + Long bookingId) { if (!request.equals("2")) { return new ArrayList<>(); } @@ -1394,7 +1353,8 @@ public class AdminAPIController { } } - private List handleBookingSettlementRequest(String request, String fromDate, String toDate, String refundStatus) { + private List handleBookingSettlementRequest(String request, String fromDate, String toDate, + String refundStatus) { if (!request.equals("6")) { return new ArrayList<>(); } @@ -1410,7 +1370,6 @@ public class AdminAPIController { return ResponseEntity.ok(halldetails); } - @GetMapping("/listgccblocking") public ResponseEntity> getGccBlocking() { @@ -1495,7 +1454,7 @@ public class AdminAPIController { @PostMapping("/uploadnoc") public ResponseEntity uploadnoc(@RequestParam("nocFile") MultipartFile file, - @RequestParam("bookingid") int bookingId) { + @RequestParam("bookingid") int bookingId) { try { System.out.println("Received file: " + file.getOriginalFilename()); System.out.println("Booking ID: " + bookingId); @@ -1504,7 +1463,8 @@ public class AdminAPIController { return ResponseEntity.ok("File uploaded and saved successfully"); } catch (Exception e) { System.err.println("Error during file upload: " + e.getMessage()); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("File upload failed: " + e.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body("File upload failed: " + e.getMessage()); } } } diff --git a/src/main/java/com/gcc/communityHall/controller/OfficerController.java b/src/main/java/com/gcc/communityHall/controller/OfficerController.java index 7ab90696..4e48263e 100644 --- a/src/main/java/com/gcc/communityHall/controller/OfficerController.java +++ b/src/main/java/com/gcc/communityHall/controller/OfficerController.java @@ -1,8 +1,15 @@ package com.gcc.communityHall.controller; import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Set; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.format.annotation.DateTimeFormat; @@ -16,6 +23,7 @@ import org.springframework.web.bind.annotation.RequestParam; import com.gcc.communityHall.entity.BookingDetails; import com.gcc.communityHall.entity.BookingDetails.RefundStatus; import com.gcc.communityHall.entity.CounterRefundList; +import com.gcc.communityHall.entity.GccBlockingDate; import com.gcc.communityHall.entity.HallDetails; import com.gcc.communityHall.entity.Payments; import com.gcc.communityHall.entity.Settlement; @@ -23,6 +31,7 @@ import com.gcc.communityHall.entity.Users; import com.gcc.communityHall.others.AppConfig; import com.gcc.communityHall.repository.BookingDetailsRepository; import com.gcc.communityHall.repository.CounterRefundListRepository; +import com.gcc.communityHall.repository.GccBlockingDateRepository; import com.gcc.communityHall.repository.HallDetailsRepository; import com.gcc.communityHall.repository.PaymentsRepository; import com.gcc.communityHall.repository.SettlementRepository; @@ -58,6 +67,8 @@ public class OfficerController { @Autowired private HallDetailService hallDetailsService; + @Autowired + private GccBlockingDateRepository blockingDateRepository; @GetMapping("/login") public String viewLoginPage(Model model) { @@ -186,7 +197,6 @@ public class OfficerController { } } - @GetMapping("/settlement-list") public String settlementPendingList(Model model, HttpSession session) { String officername = (String) session.getAttribute("usertype"); @@ -200,16 +210,17 @@ public class OfficerController { model.addAttribute("zone", zone); System.out.println("Zone: " + zone); List settlement = bookingDetailsRepository.findSettlementPendingByZone(zone); - //ak - List settlementIntiated = bookingDetailsRepository.findSettlementInitiatedPendingByZone(zone); + // ak + List settlementIntiated = bookingDetailsRepository + .findSettlementInitiatedPendingByZone(zone); List cancelledbookings = bookingDetailsRepository.findCancelledListByZone(zone); List rejectedbookings = bookingDetailsRepository.findRejectedListByZone(zone); model.addAttribute("settlementlist", settlement); - //AK + // AK model.addAttribute("settlementIntiated", settlementIntiated); model.addAttribute("cancelledbookings", cancelledbookings); model.addAttribute("rejectedbookings", rejectedbookings); - System.out.println("settlementIntiated"+settlementIntiated); + System.out.println("settlementIntiated" + settlementIntiated); return "officer/settlement-list"; } else { session.invalidate(); @@ -228,9 +239,12 @@ public class OfficerController { model.addAttribute("baseURL", appConfig.getBaseUrl()); String zone = (String) session.getAttribute("zone"); model.addAttribute("zone", zone); - List settlementrefundfailed = bookingDetailsRepository.findSettlementRefundFailedByZone(zone); - List refundfailedcancelledbookings = bookingDetailsRepository.findRefundFaileCancelledListByZone(zone); - List refundfailedrejectedbookings = bookingDetailsRepository.findRefundFaileRejectedListByZone(zone); + List settlementrefundfailed = bookingDetailsRepository + .findSettlementRefundFailedByZone(zone); + List refundfailedcancelledbookings = bookingDetailsRepository + .findRefundFaileCancelledListByZone(zone); + List refundfailedrejectedbookings = bookingDetailsRepository + .findRefundFaileRejectedListByZone(zone); model.addAttribute("settlementrefundfailed", settlementrefundfailed); model.addAttribute("refundfailedcancelledbookings", refundfailedcancelledbookings); model.addAttribute("refundfailedrejectedbookings", refundfailedrejectedbookings); @@ -253,8 +267,10 @@ public class OfficerController { String zone = (String) session.getAttribute("zone"); model.addAttribute("zone", zone); List settlement = bookingDetailsRepository.findSettlementApprovedByZone(zone); - List approvedcancelledbookings = bookingDetailsRepository.findapprovedCancelledListByZone(zone); - List approvedrejectedbookings = bookingDetailsRepository.findapprovedRejectedListByZone(zone); + List approvedcancelledbookings = bookingDetailsRepository + .findapprovedCancelledListByZone(zone); + List approvedrejectedbookings = bookingDetailsRepository + .findapprovedRejectedListByZone(zone); model.addAttribute("approvedSettlementlist", settlement); model.addAttribute("approvedcancelledbookings", approvedcancelledbookings); model.addAttribute("approvedrejectedbookings", approvedrejectedbookings); @@ -294,8 +310,10 @@ public class OfficerController { String zone = (String) session.getAttribute("zone"); model.addAttribute("zone", zone); List completedlist = bookingDetailsRepository.findSettlementCompletedListbyzone(zone); - List cancelledcompletedlist = bookingDetailsRepository.findCancelledCompletedListbyzone(zone); - List rejectedcompletedlist = bookingDetailsRepository.findRejectedSettlementCompletedListbyzone(zone); + List cancelledcompletedlist = bookingDetailsRepository + .findCancelledCompletedListbyzone(zone); + List rejectedcompletedlist = bookingDetailsRepository + .findRejectedSettlementCompletedListbyzone(zone); model.addAttribute("title", "settlement initiate"); model.addAttribute("officername", officername); model.addAttribute("completedlist", completedlist); @@ -346,13 +364,13 @@ public class OfficerController { @PostMapping("/getReport") public String generateReport(Model model, HttpSession session, - @RequestParam(name = "FromDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) String fromDate, - @RequestParam(name = "ToDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) String toDate, - @RequestParam(name = "request") String request, - @RequestParam(name = "bookingStatus", required = false) String bookingStatus, - @RequestParam(name = "filterby", required = false) String filterby, - @RequestParam(name = "refundStatus", required = false) String refundStatus, - @RequestParam(name = "hallname", required = false, defaultValue = "0") Integer hallId) { + @RequestParam(name = "FromDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) String fromDate, + @RequestParam(name = "ToDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) String toDate, + @RequestParam(name = "request") String request, + @RequestParam(name = "bookingStatus", required = false) String bookingStatus, + @RequestParam(name = "filterby", required = false) String filterby, + @RequestParam(name = "refundStatus", required = false) String refundStatus, + @RequestParam(name = "hallname", required = false, defaultValue = "0") Integer hallId) { String officername = (String) session.getAttribute("usertype"); if (officername != null) { String zone = (String) session.getAttribute("zone"); @@ -362,10 +380,15 @@ public class OfficerController { model.addAttribute("mobileno", mobileno); List hallnames = hallDetailsService.getHallNamesbyzone(zone); model.addAttribute("hallnames", hallnames); - List bookingList = handleBookingRequest(request, fromDate, toDate, bookingStatus, zone, filterby); - List bookingSettlementList = handleBookingSettlementRequest(request, fromDate, toDate, refundStatus, zone, filterby); - List paymentList = request.equals("3") ? bookingService.getAllPaymentsDetailsByZone(fromDate, toDate, zone) : new ArrayList<>(); - List hallbookingList = handleHallBookingRequest(request, fromDate, toDate, zone, hallId, filterby); + List bookingList = handleBookingRequest(request, fromDate, toDate, bookingStatus, zone, + filterby); + List bookingSettlementList = handleBookingSettlementRequest(request, fromDate, toDate, + refundStatus, zone, filterby); + List paymentList = request.equals("3") + ? bookingService.getAllPaymentsDetailsByZone(fromDate, toDate, zone) + : new ArrayList<>(); + List hallbookingList = handleHallBookingRequest(request, fromDate, toDate, zone, hallId, + filterby); model.addAttribute("bookings", bookingList); model.addAttribute("bookingSettlementList", bookingSettlementList); model.addAttribute("bookingStatus", bookingStatus); @@ -384,8 +407,8 @@ public class OfficerController { } } - - private List handleBookingRequest(String request, String fromDate, String toDate, String bookingStatus, String zone, String filterby) { + private List handleBookingRequest(String request, String fromDate, String toDate, + String bookingStatus, String zone, String filterby) { if (!request.equals("1")) { return new ArrayList<>(); } @@ -393,7 +416,8 @@ public class OfficerController { return bookingService.getAllBookingDetailsBookingDateByZone(fromDate, toDate, zone); } if (filterby.isEmpty() && !bookingStatus.isEmpty()) { - return bookingService.getAllBookingDetailsBookingDateByZoneWithStatus(fromDate, toDate, zone, bookingStatus); + return bookingService.getAllBookingDetailsBookingDateByZoneWithStatus(fromDate, toDate, zone, + bookingStatus); } if (!filterby.isEmpty()) { @@ -401,7 +425,8 @@ public class OfficerController { if (bookingStatus.isEmpty()) { return bookingService.getAllBookingDetailsBookingDateByZone(fromDate, toDate, zone); } else { - return bookingService.getAllBookingDetailsBookingDateByZoneWithStatus(fromDate, toDate, zone, bookingStatus); + return bookingService.getAllBookingDetailsBookingDateByZoneWithStatus(fromDate, toDate, zone, + bookingStatus); } @@ -410,7 +435,8 @@ public class OfficerController { if (bookingStatus.isEmpty()) { return bookingService.getAllBookingDetailsEventDateByZone(fromDate, toDate, zone); } else { - return bookingService.getAllBookingDetailsEventDateByZoneWithStatus(fromDate, toDate, zone, bookingStatus); + return bookingService.getAllBookingDetailsEventDateByZoneWithStatus(fromDate, toDate, zone, + bookingStatus); } } @@ -419,7 +445,8 @@ public class OfficerController { return new ArrayList<>(); } - private List handleBookingSettlementRequest(String request, String fromDate, String toDate, String refundStatus, String zone, String filterby) { + private List handleBookingSettlementRequest(String request, String fromDate, String toDate, + String refundStatus, String zone, String filterby) { if (!request.equals("2")) { return new ArrayList<>(); } @@ -427,7 +454,8 @@ public class OfficerController { return bookingService.getAllBookingsettlementDetailsByZoneByBookingDate(fromDate, toDate, zone); } if ((refundStatus != null && !refundStatus.isEmpty()) && filterby.isEmpty()) { - return bookingService.getAllBookingsettlementDetailsByZoneByBookingDateWithStatus(fromDate, toDate, zone, refundStatus); + return bookingService.getAllBookingsettlementDetailsByZoneByBookingDateWithStatus(fromDate, toDate, zone, + refundStatus); } if (!filterby.isEmpty()) { @@ -435,7 +463,8 @@ public class OfficerController { if (refundStatus.isEmpty() || refundStatus == null) { return bookingService.getAllBookingsettlementDetailsByZoneByBookingDate(fromDate, toDate, zone); } else { - return bookingService.getAllBookingsettlementDetailsByZoneByBookingDateWithStatus(fromDate, toDate, zone, refundStatus); + return bookingService.getAllBookingsettlementDetailsByZoneByBookingDateWithStatus(fromDate, toDate, + zone, refundStatus); } } @@ -443,18 +472,19 @@ public class OfficerController { if (refundStatus.isEmpty() || refundStatus == null) { return bookingService.getAllBookingsettlementDetailsByZoneByEventDate(fromDate, toDate, zone); } else { - return bookingService.getAllBookingsettlementDetailsByZoneByEventDateWithStatus(fromDate, toDate, zone, refundStatus); + return bookingService.getAllBookingsettlementDetailsByZoneByEventDateWithStatus(fromDate, toDate, + zone, refundStatus); } } } - return new ArrayList<>(); } - private List handleHallBookingRequest(String request, String fromDate, String toDate, String zone, Integer hallId, String filterby) { + private List handleHallBookingRequest(String request, String fromDate, String toDate, String zone, + Integer hallId, String filterby) { if (!request.equals("4")) { return new ArrayList<>(); } @@ -462,19 +492,22 @@ public class OfficerController { return bookingService.getBookingHallDetailsReportByZoneByBookingDate(fromDate, toDate, zone); } if (filterby.isEmpty() && hallId != 0) { - return bookingService.getBookingHallDetailsReportByZoneByBookingDateHallname(fromDate, toDate, zone, hallId); + return bookingService.getBookingHallDetailsReportByZoneByBookingDateHallname(fromDate, toDate, zone, + hallId); } if (!filterby.isEmpty()) { if ("1".equals(filterby)) { if (hallId != 0) { - return bookingService.getBookingHallDetailsReportByZoneByBookingDateHallname(fromDate, toDate, zone, hallId); + return bookingService.getBookingHallDetailsReportByZoneByBookingDateHallname(fromDate, toDate, zone, + hallId); } else { return bookingService.getBookingHallDetailsReportByZoneByBookingDate(fromDate, toDate, zone); } } if ("2".equals(filterby)) { if (hallId != 0) { - return bookingService.getBookingHallDetailsReportByZoneByEventDateHallname(fromDate, toDate, zone, hallId); + return bookingService.getBookingHallDetailsReportByZoneByEventDateHallname(fromDate, toDate, zone, + hallId); } else { return bookingService.getBookingHallDetailsReportByZoneByEventDate(fromDate, toDate, zone); } @@ -483,7 +516,6 @@ public class OfficerController { return new ArrayList<>(); } - @GetMapping("/counter-refund") public String counterRefundList(Model model, HttpSession session) { String officername = (String) session.getAttribute("usertype"); @@ -509,4 +541,56 @@ public class OfficerController { session.invalidate(); return "redirect:/communityhall/login"; } + + // Newly added for zone level block + + @GetMapping("/Gccblocking") + public String viewGccBlocking(Model model, HttpSession session) { + String officername = (String) session.getAttribute("usertype"); + if (officername != null) { + long mobileno = (long) session.getAttribute("mobileno"); + model.addAttribute("mobileno", mobileno); + model.addAttribute("officername", officername); + // Fetch all blocked GCC dates + List gccBlocked = blockingDateRepository.findAllBlocked(); + + // Ensure distinct by hallId, blockingReason, startDate, and endDate + List uniqueGccBlockingDates = gccBlocked.stream() + .filter(distinctByKey(g -> Arrays.asList( + g.getHallId(), + g.getBlockingReason(), + g.getStartDate(), + g.getEndDate()))) + .collect(Collectors.toList()); + + // Map to store the count of blocked halls for each GccBlockingDate + Map hallCountMap = new HashMap<>(); + for (GccBlockingDate blockedDate : uniqueGccBlockingDates) { + // Parse and count unique hall IDs + String hallIds = blockedDate.getHallId(); + if (hallIds != null && !hallIds.isEmpty()) { + Set uniqueHallIds = new HashSet<>(Arrays.asList(hallIds.split(","))); + int hallCount = uniqueHallIds.size(); + hallCountMap.put(blockedDate.getBlockingId(), hallCount); + } else { + hallCountMap.put(blockedDate.getBlockingId(), 0); // No halls blocked + } + } + + // Add attributes to the model for the view + model.addAttribute("gccblocked", uniqueGccBlockingDates); + model.addAttribute("hallCountMap", hallCountMap); + + return "officer/gccblocking"; + } else { + session.invalidate(); // Invalidate the session to clear all session attributes + return "redirect:/communityhall/login"; + } + } + + // Utility method to ensure distinct by a key + private static Predicate distinctByKey(Function keyExtractor) { + Set seen = new HashSet<>(); + return t -> seen.add(keyExtractor.apply(t)); + } } diff --git a/src/main/java/com/gcc/communityHall/controller/UserAPIController.java b/src/main/java/com/gcc/communityHall/controller/UserAPIController.java index 03e9f802..63e7b010 100644 --- a/src/main/java/com/gcc/communityHall/controller/UserAPIController.java +++ b/src/main/java/com/gcc/communityHall/controller/UserAPIController.java @@ -1,6 +1,5 @@ package com.gcc.communityHall.controller; - import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -112,11 +111,7 @@ import org.springframework.util.StreamUtils; import java.io.IOException; import java.nio.charset.StandardCharsets; - -@Tag( - name = "CRUD REST APIs for User in CommunityHall", - description = "CRUD REST APIs in CommunityHall to CREATE, UPDATE, FETCH AND DELETE Booking details" -) +@Tag(name = "CRUD REST APIs for User in CommunityHall", description = "CRUD REST APIs in CommunityHall to CREATE, UPDATE, FETCH AND DELETE Booking details") @RestController @RequestMapping("/communityhall/user/api") @AllArgsConstructor @@ -181,37 +176,30 @@ public class UserAPIController { this.uploadDirectory = uploadDirectory; } - @Operation( - summary = "Retrieving the HallDetails by HallId REST API", - description = "REST API to Retrieving the HallDetails by HallId" - ) + @Operation(summary = "Retrieving the HallDetails by HallId REST API", description = "REST API to Retrieving the HallDetails by HallId") @ApiResponses({ - @ApiResponse( - responseCode = "200", - description = "HTTP Status UPDATED" - ), - @ApiResponse( - responseCode = "500", - description = "HTTP Status Internal Server Error", - content = @Content( - schema = @Schema(implementation = ErrorResponseDto.class) - ) - ) - } - ) - //retrieving Hall Details by HallId + @ApiResponse(responseCode = "200", description = "HTTP Status UPDATED"), + @ApiResponse(responseCode = "500", description = "HTTP Status Internal Server Error", content = @Content(schema = @Schema(implementation = ErrorResponseDto.class))) + }) + // retrieving Hall Details by HallId @GetMapping("/gethalldetails/{hallId}") public ResponseEntity getHallDetails(@PathVariable int hallId) { - Optional hallDetails = hallDetailsRepository.findById(hallId); - return hallDetails.map(ResponseEntity::ok) - .orElseGet(() -> ResponseEntity.status(404).body(null)); - } + // Optional hallDetails = hallDetailsRepository.findById(hallId); + // return hallDetails.map(ResponseEntity::ok) + // .orElseGet(() -> ResponseEntity.status(404).body(null)); - @Operation( - summary = "Retrieving the Hallnames only REST API", - description = "REST API to Retrieving the Hallnames only" - ) + HallDetails hallDetails = hallDetailsRepository.findHallActiveDetailsById(hallId); + System.out.println("hallDetails.." + hallDetails); + + if (hallDetails != null) { + return ResponseEntity.ok(hallDetails); + } else { + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); + } + } + + @Operation(summary = "Retrieving the Hallnames only REST API", description = "REST API to Retrieving the Hallnames only") @GetMapping("/gethallnames") public ResponseEntity> getHallNames() { @@ -223,62 +211,63 @@ public class UserAPIController { hallData.setHallName(hallDetails.getHallName()); hallDataList.add(hallData); } - return ResponseEntity.ok(hallDataList); // Return ResponseEntity with list of HallData objects containing only id and hallname + return ResponseEntity.ok(hallDataList); // Return ResponseEntity with list of HallData objects containing only + // id and hallname } - - @Operation( - summary = "Send OTP REST API", - description = "REST API For Sending OTP to user" - ) - //SendOTP + @Operation(summary = "Send OTP REST API", description = "REST API For Sending OTP to user") + // SendOTP @GetMapping(value = "/sendOTP") public String sendOtp(HttpServletRequest request, @RequestParam Long mobileNo, @RequestParam String purpose) { Long MobileNo = mobileNo; - //System.out.println(purpose); - //System.out.print("\n MobileNo---:"+mobileNo); + // System.out.println(purpose); + // System.out.print("\n MobileNo---:"+mobileNo); Random rand = new Random(); - int otp = rand.nextInt(90000) + 10000; + int otp = rand.nextInt(90000) + 10000; // int otp = 11111; System.out.print("\n otp---:" + otp); DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MMM-yyyy%20HH:mm"); LocalDateTime now = LocalDateTime.now(); - //System.out.println(dtf.format(now)); + // System.out.println(dtf.format(now)); String key = "pfTEYN6H"; String generatedToken = "Welcome to GCC! Your OTP for GCC Community Centre is " + otp; - String urlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + mobileNo + "&from=GCCCRP&body=Welcome to GCC! Your OTP for GCC Community Centre booking is " + otp + "&entityid=1401572690000011081&templateid=1407172346444550398"; + String urlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + mobileNo + + "&from=GCCCRP&body=Welcome to GCC! Your OTP for GCC Community Centre booking is " + otp + + "&entityid=1401572690000011081&templateid=1407172346444550398"; System.out.println(urlString); System.out.println("\n urlString---: " + urlString); String bodyMessage = "" + otp; try { - RestTemplate restTemplate = new RestTemplate(); - String Response = restTemplate.getForObject(urlString, String.class); - bodyMessage=Response; - SmsSender sms = new SmsSender(); - sms.setPhone(MobileNo); - sms.setCdate(new Date()); - sms.setBodyMsg(bodyMessage); - sms.setPurpose(purpose); - smsSenderRepository.save(sms); - - String whatsappMsg="https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to="+MobileNo+"&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Welcome+to+GCC%21+%0A%0AYour+OTP+for+GCC+Community+Centre+is+"+otp+"+."; - String sendMsg = whatsappMsgServiceImpl.sendMsg(whatsappMsg); - System.out.println("sendwhatsuprepsosne===="+sendMsg); + RestTemplate restTemplate = new RestTemplate(); + String Response = restTemplate.getForObject(urlString, String.class); + bodyMessage = Response; + SmsSender sms = new SmsSender(); + sms.setPhone(MobileNo); + sms.setCdate(new Date()); + sms.setBodyMsg(bodyMessage); + sms.setPurpose(purpose); + smsSenderRepository.save(sms); + + String whatsappMsg = + "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + + MobileNo + + + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Welcome+to+GCC%21+%0A%0AYour+OTP+for+GCC+Community+Centre+is+" + + otp + "+."; + String sendMsg = whatsappMsgServiceImpl.sendMsg(whatsappMsg); + System.out.println("sendwhatsuprepsosne====" + sendMsg); } catch (Exception e) { - // System.out.print("ERROR in Sending---: "+e); - bodyMessage = "Error"; + // System.out.print("ERROR in Sending---: "+e); + bodyMessage = "Error"; } HttpSession session = request.getSession(); session.setAttribute("otp", otp); return bodyMessage; } - @Operation( - summary = "Vetify OTP REST API", - description = "REST API For verifying OTP" - ) - //VerifyOTP + @Operation(summary = "Vetify OTP REST API", description = "REST API For verifying OTP") + // VerifyOTP @GetMapping(value = "/verifyOTP") public String verifyOtp(HttpServletRequest request, @RequestParam String otp, @RequestParam long mobileNo) { HttpSession session = request.getSession(); @@ -292,7 +281,7 @@ public class UserAPIController { Users user = userservice.findByMobileno(mobileNo); if (user != null) { userSession.setMobileno(user.getMobileNo()); - //userSession.setUserType(user.getUserType()); + // userSession.setUserType(user.getUserType()); userSession.setDispayName(user.getName()); userSession.setUserId(user.getUserId()); String userType = user.getUsertype().toString(); @@ -310,7 +299,7 @@ public class UserAPIController { return "Error"; } } catch (NumberFormatException e) { - //System.out.println("Invalid OTP format: " + otp); + // System.out.println("Invalid OTP format: " + otp); return "Error"; } catch (Exception e) { // System.out.println("Error verifying OTP: " + e.getMessage()); @@ -327,7 +316,7 @@ public class UserAPIController { Integer entered_otp = Integer.parseInt(otp); if (session_otp != null && session_otp.equals(entered_otp)) { - //System.out.println("Entered OTP Correct"); + // System.out.println("Entered OTP Correct"); session.setAttribute("verifiedotp", "success"); return "Success"; } else { @@ -339,16 +328,13 @@ public class UserAPIController { // System.out.println("Invalid OTP format: " + otp); return "Error"; } catch (Exception e) { - //System.out.println("Error verifying OTP: " + e.getMessage()); + // System.out.println("Error verifying OTP: " + e.getMessage()); return "Error"; } } - @Operation( - summary = "User Mobileno Validation REST API", - description = "REST API For Validating User with Mobileno" - ) - //Validating User with the mobileno + @Operation(summary = "User Mobileno Validation REST API", description = "REST API For Validating User with Mobileno") + // Validating User with the mobileno @GetMapping(value = "/checkMobileExits") public String checkMobileExits(@RequestParam long mobileno) { try { @@ -368,32 +354,31 @@ public class UserAPIController { } } - @Operation( - summary = "Cousellor Mobileno Validation REST API", - description = "REST API For Validating the Counsellor Mobileno" - ) - //Counsellor Mobile no Validation + @Operation(summary = "Cousellor Mobileno Validation REST API", description = "REST API For Validating the Counsellor Mobileno") + // Counsellor Mobile no Validation @GetMapping(value = "/checkCounsellorMobileExits") public ResponseEntity checkCounsellorMobileExits(@RequestParam long mobileno) { // Find the counsellor by the provided mobile number - Counsellordetails counsellor = userservice.findByMobile(mobileno); // This checks both mobileNo1 and mobileNo2 in the counsellor table + Counsellordetails counsellor = userservice.findByMobile(mobileno); // This checks both mobileNo1 and mobileNo2 + // in the counsellor table if (counsellor == null) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Counsellor Mobile Number Not Found"); } - // Check if mobileNo1 or mobileNo2 of the counsellor is already used in the Users table + // Check if mobileNo1 or mobileNo2 of the counsellor is already used in the + // Users table boolean isMobile1Used = usersRepository.existsByMobileNo(counsellor.getMobile1()); boolean isMobile2Used = usersRepository.existsByMobileNo(counsellor.getMobile2()); if (isMobile1Used || isMobile2Used) { - return ResponseEntity.status(HttpStatus.CONFLICT).body("One of the counsellor's mobile numbers is already used."); + return ResponseEntity.status(HttpStatus.CONFLICT) + .body("One of the counsellor's mobile numbers is already used."); } // If no conflict, return success with the counsellor's name return ResponseEntity.ok(counsellor.getName()); } - @GetMapping("/checkEmployee") public Map checkEmployee(@RequestParam String id) { boolean isRegistered = usersRepository.existsByGovernmentId(id); @@ -402,22 +387,15 @@ public class UserAPIController { return response; } - - @Operation( - summary = "Retriving the zone REST API", - description = "REST API to Retriev the zone for displaying in Frontend" - ) - //retrieving the zone + @Operation(summary = "Retriving the zone REST API", description = "REST API to Retriev the zone for displaying in Frontend") + // retrieving the zone @GetMapping(value = "/getZone") public List> getZone() { return hallDetailsRepository.getZoneAndDivision(); } - @Operation( - summary = "Zones by Hall REST API", - description = "REST API to Retrieve the zone by Hall for displaying in GccBlocking page" - ) - //retrieving the zones by hall + @Operation(summary = "Zones by Hall REST API", description = "REST API to Retrieve the zone by Hall for displaying in GccBlocking page") + // retrieving the zones by hall @GetMapping(value = "/hallsbyzone") public List> getHallsByZone(@RequestParam(required = false) String zones) { if (zones == null || zones.isEmpty()) { @@ -428,11 +406,8 @@ public class UserAPIController { } } - @Operation( - summary = "Past Data from the booking Calendar Hall REST API", - description = "REST API to Retrieve the Pat Data from booking calendar" - ) - //Getting the Past Data from the Calendar + @Operation(summary = "Past Data from the booking Calendar Hall REST API", description = "REST API to Retrieve the Pat Data from booking calendar") + // Getting the Past Data from the Calendar @GetMapping("/getPastData") public List getPastData(@RequestParam("hall_id") int hall_id) { List data = new ArrayList(); @@ -443,17 +418,14 @@ public class UserAPIController { return data; } - @Operation( - summary = "Pensioner Details ERP REST API", - description = "REST API to retrieving the Pensioner Details From ERP" - ) - //retrieving the Pensioner Details From ERP + @Operation(summary = "Pensioner Details ERP REST API", description = "REST API to retrieving the Pensioner Details From ERP") + // retrieving the Pensioner Details From ERP @GetMapping("/PensionerDetail") public PensionerDetailsResponse getPensionerDetails(@RequestParam("pensionerId") String pensionerId) { - //System.out.println(pensionerId); + // System.out.println(pensionerId); RestTemplate restTemplate = new RestTemplate(); - String url = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?serviceId=getPensionerDetailsList&pensionerId=" + pensionerId; - + String url = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?serviceId=getPensionerDetailsList&pensionerId=" + + pensionerId; ResponseEntity responseEntity = restTemplate.getForEntity(url, String.class); @@ -463,7 +435,8 @@ public class UserAPIController { // Extract the Java object from the response body ObjectMapper objectMapper = new ObjectMapper(); try { - PensionerDetailsResponse pensionerResponse = objectMapper.readValue(jsonString, PensionerDetailsResponse.class); + PensionerDetailsResponse pensionerResponse = objectMapper.readValue(jsonString, + PensionerDetailsResponse.class); // Now you can access the pensionerResponse object as usual // e.g., pensionerResponse.getPensioners() to get the list of pensioners @@ -474,20 +447,17 @@ public class UserAPIController { e.printStackTrace(); return null; } - //return null; + // return null; } - @Operation( - summary = "Employee Details ERP REST API", - description = "REST API to retrieving the Employee Details From ERP" - ) + @Operation(summary = "Employee Details ERP REST API", description = "REST API to retrieving the Employee Details From ERP") @GetMapping("/EmployeeDetails") public EmployeeDetailsResponse getEmployeeDetails(@RequestParam("employeeId") Long employeeId) { - //System.out.println("Employee ID:"+employeeId); + // System.out.println("Employee ID:"+employeeId); RestTemplate restTemplate = new RestTemplate(); - String url = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?serviceId=getEmployeeDetail&EmployeeID=" + employeeId; - + String url = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?serviceId=getEmployeeDetail&EmployeeID=" + + employeeId + "&forCC=Yes"; ResponseEntity responseEntity = restTemplate.getForEntity(url, String.class); @@ -497,7 +467,8 @@ public class UserAPIController { // Extract the Java object from the response body ObjectMapper objectMapper = new ObjectMapper(); try { - EmployeeDetailsResponse employeeResponse = objectMapper.readValue(jsonString, EmployeeDetailsResponse.class); + EmployeeDetailsResponse employeeResponse = objectMapper.readValue(jsonString, + EmployeeDetailsResponse.class); // Now you can access the pensionerResponse object as usual // e.g., pensionerResponse.getPensioners() to get the list of pensioners @@ -508,20 +479,17 @@ public class UserAPIController { e.printStackTrace(); return null; } - //return null; + // return null; } - @Operation( - summary = "FamilyPensioner Details ERP REST API", - description = "REST API to retrieving the FamilyPensioner Details From ERP" - ) - //retrieving the FamilyPensionerDetails Details From ERP + @Operation(summary = "FamilyPensioner Details ERP REST API", description = "REST API to retrieving the FamilyPensioner Details From ERP") + // retrieving the FamilyPensionerDetails Details From ERP @GetMapping("/FamilyPensionerDetail") public FamilyPensionerDetailsResponse getFamilyPensionerDetails(@RequestParam("id") Long id) { RestTemplate restTemplate = new RestTemplate(); - String url = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?serviceId=getFamPensionerDetailsList&familPensionId=" + id; - + String url = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?serviceId=getFamPensionerDetailsList&familPensionId=" + + id; ResponseEntity responseEntity = restTemplate.getForEntity(url, String.class); @@ -531,7 +499,8 @@ public class UserAPIController { // Extract the Java object from the response body ObjectMapper objectMapper = new ObjectMapper(); try { - FamilyPensionerDetailsResponse familyPensionerDetailsResponse = objectMapper.readValue(jsonString, FamilyPensionerDetailsResponse.class); + FamilyPensionerDetailsResponse familyPensionerDetailsResponse = objectMapper.readValue(jsonString, + FamilyPensionerDetailsResponse.class); // Now you can access the pensionerResponse object as usual // e.g., pensionerResponse.getPensioners() to get the list of pensioners @@ -544,11 +513,8 @@ public class UserAPIController { } } - @Operation( - summary = "Hall Details coordinates REST API", - description = "REST API to retrieving the Hall Details coordinates for Map" - ) - //retrieving the All Hall Details coordinates + @Operation(summary = "Hall Details coordinates REST API", description = "REST API to retrieving the Hall Details coordinates for Map") + // retrieving the All Hall Details coordinates @GetMapping("/getallhallcoordinates") public List> getAllHallCoordinates() { List allHallDetails = hallDetailsRepository.findActiveHalls(); @@ -576,11 +542,8 @@ public class UserAPIController { return details; } - @Operation( - summary = "Booking Limitation Details ERP REST API", - description = "REST API to check the Booking Limitation & UserStatus pending" - ) - //Booking Limitation & UserStatus pending + @Operation(summary = "Booking Limitation Details ERP REST API", description = "REST API to check the Booking Limitation & UserStatus pending") + // Booking Limitation & UserStatus pending @GetMapping("/bookingLimit") public String CheckbookingLimitation(Model model) { int userId = userSession.getUserId(); @@ -592,18 +555,15 @@ public class UserAPIController { return "rejected"; } int checkUserBookingLimitation = bookingService.checkUserBookinglimitation(userId); -// System.out.println("checkUserBookingLimitation="+checkUserBookingLimitation); + // System.out.println("checkUserBookingLimitation="+checkUserBookingLimitation); if (checkUserBookingLimitation < 2) { -// System.out.println("checkUserBookingLimitationss="+checkUserBookingLimitation); + // System.out.println("checkUserBookingLimitationss="+checkUserBookingLimitation); return "success"; } return "failure"; } - @Operation( - summary = "Counter Booikng Limit REST API", - description = "REST API to check the Counter Booking Limitation" - ) + @Operation(summary = "Counter Booikng Limit REST API", description = "REST API to check the Counter Booking Limitation") @GetMapping("/counterbookinglimit") public String checkCounterBookingLimitation(@RequestParam long mobileNo) { Users user = userService.getUserDetailsByMobileNo(mobileNo); @@ -626,14 +586,12 @@ public class UserAPIController { return "checkmobilenoexists"; } - @Operation( - summary = "User Status Pending REST API", - description = "REST API to check User Status is Pending and not allow user to login" - ) - //UserStatus pending + @Operation(summary = "User Status Pending REST API", description = "REST API to check User Status is Pending and not allow user to login") + // UserStatus pending @GetMapping("/checkuserstatus") public String checkUserStatus(@RequestParam long mobileNo) { - Users user = userService.getUserDetailsByMobileNo(mobileNo); // Assuming you have a method to retrieve a user by mobile number + Users user = userService.getUserDetailsByMobileNo(mobileNo); // Assuming you have a method to retrieve a user by + // mobile number if (user != null && user.getUserstatus() == Users.userStatus.PENDING) { return "pending"; } @@ -643,11 +601,8 @@ public class UserAPIController { return "checkmobileexist"; } - @Operation( - summary = "Username and Mobileno from userSession REST API", - description = "REST API to get the Username and Mobileno from userSession" - ) - //Getting Username and Mobileno from userSession + @Operation(summary = "Username and Mobileno from userSession REST API", description = "REST API to get the Username and Mobileno from userSession") + // Getting Username and Mobileno from userSession @GetMapping("/getUsername") public ResponseEntity> checkUsername() { Map userDetails = new HashMap<>(); @@ -663,10 +618,7 @@ public class UserAPIController { return hallDetailsRepository.getZonesAndDivisions(); } - @Operation( - summary = "ZONES from ERP REST API", - description = "REST API to get the zones from ERP" - ) + @Operation(summary = "ZONES from ERP REST API", description = "REST API to get the zones from ERP") // Rest Api From ERP for getting Zones @GetMapping(value = "/getZoneNo") public String getZoneNo() { @@ -680,19 +632,16 @@ public class UserAPIController { HttpEntity postData = new HttpEntity(headers); response = restTemplate.exchange(urlString, HttpMethod.POST, postData, String.class); bodyMessage = response.getBody(); - //System.out.println("BodyMessage" + bodyMessage); + // System.out.println("BodyMessage" + bodyMessage); } catch (Exception e) { e.printStackTrace(); - //System.out.print("\n ERROR---: " + e); + // System.out.print("\n ERROR---: " + e); bodyMessage = "Error"; } return bodyMessage; } - @Operation( - summary = "DIVISIONS from ERP REST API", - description = "REST API to get the divisions from ERP" - ) + @Operation(summary = "DIVISIONS from ERP REST API", description = "REST API to get the divisions from ERP") // Rest Api From ERP for getting Divisions @GetMapping(value = "/getDiv") public String getDiv(@RequestParam String zoneId) { @@ -705,59 +654,54 @@ public class UserAPIController { HttpEntity postData = new HttpEntity(headers); response = restTemplate.exchange(urlString, HttpMethod.POST, postData, String.class); bodyMessage = response.getBody(); - //System.out.println("bodyMessage" + bodyMessage); + // System.out.println("bodyMessage" + bodyMessage); } catch (Exception e) { e.printStackTrace(); - //System.out.print("\n ERROR---: " + e); + // System.out.print("\n ERROR---: " + e); bodyMessage = "Error"; } return bodyMessage; } - @Operation( - summary = "HAlls By Division ERP REST API", - description = "REST API to get the HAlls by Divisions" - ) - //retrieving the Halls By Division + @Operation(summary = "HAlls By Division ERP REST API", description = "REST API to get the HAlls by Divisions") + // retrieving the Halls By Division @GetMapping("/hallsbydivision") public List getHallsByDivision(@RequestParam("division") String division) { - return hallDetailsRepository.findByDivision(division); + return hallDetailsRepository.findActiveHallsByDivision(division); } - @Operation( - summary = "HAlls By zone ERP REST API", - description = "REST API to get the HAlls by zone" - ) + @Operation(summary = "HAlls By zone ERP REST API", description = "REST API to get the HAlls by zone") @GetMapping("/findhallsbyzone") public List getHallsByzone(@RequestParam("zone") String zone) { - return hallDetailsRepository.findByZone(zone); + return hallDetailsRepository.findActiveHallsByZone(zone); } - @Operation( - summary = "Booking Details By bookingId ERP REST API", - description = "REST API to get the Booking Details based on BookingId" - ) - //retrieving the Booking Details based on BookingId + @Operation(summary = "Booking Details By bookingId ERP REST API", description = "REST API to get the Booking Details based on BookingId") + // retrieving the Booking Details based on BookingId @GetMapping("/viewAllBookingDetails") public ResponseEntity getUserDetailsByBookingId(@RequestParam("bookingId") int bookingId) { LocalDateTime rescheduledUpdatedDate = null; BookingDetails bookingDetails = bookingService.getBookingsById(bookingId); - /*if (bookingDetails.getComments().equals("slots Resheduled the Dates")) { - rescheduledUpdatedDate = LocalDateTime.parse(bookingDetails.getUpdatedDate()); - } else if(bookingDetails.getScheduleCount()==1){ - List histories = bookingDetails.getBookingHistories(); - - if (histories != null && !histories.isEmpty()) { - rescheduledUpdatedDate = histories.stream() - .filter(history -> "slots Resheduled the Dates".equals(history.getComments())) - .map(BookingHistory::getUpdatedDate) - .findFirst() - .orElse(null); } - - }*/ + /* + * if (bookingDetails.getComments().equals("slots Resheduled the Dates")) { + * rescheduledUpdatedDate = + * LocalDateTime.parse(bookingDetails.getUpdatedDate()); + * } else if(bookingDetails.getScheduleCount()==1){ + * List histories = bookingDetails.getBookingHistories(); + * + * if (histories != null && !histories.isEmpty()) { + * rescheduledUpdatedDate = histories.stream() + * .filter(history -> + * "slots Resheduled the Dates".equals(history.getComments())) + * .map(BookingHistory::getUpdatedDate) + * .findFirst() + * .orElse(null); } + * + * } + */ if (bookingDetails != null) { return ResponseEntity.ok(bookingDetails); @@ -766,11 +710,8 @@ public class UserAPIController { } } - @Operation( - summary = "New Registration in Counter REST API", - description = "REST API for New Registration in Counter" - ) - //New Registration in Counter + @Operation(summary = "New Registration in Counter REST API", description = "REST API for New Registration in Counter") + // New Registration in Counter @PostMapping("/newcounterregistrationform") public ResponseEntity showRegistrationForm( @ModelAttribute Users counterform, @@ -803,12 +744,8 @@ public class UserAPIController { } } - - @Operation( - summary = "Counter User Details REST API", - description = "REST API to get the User Details by Mobileno for counter" - ) - //retrieving the User Details by Mobileno for Counter + @Operation(summary = "Counter User Details REST API", description = "REST API to get the User Details by Mobileno for counter") + // retrieving the User Details by Mobileno for Counter @GetMapping("/getUserDetails") public ResponseEntity getUserDetailsByMobileNo(@RequestParam("mobileNo") long mobileNo) { try { @@ -826,49 +763,44 @@ public class UserAPIController { } } - @Operation( - summary = "DD Image by CounterID REST API", - description = "REST API to get the DD Image by counterId" - ) - //retrieving the Dd Image by counterId + @Operation(summary = "DD Image by CounterID REST API", description = "REST API to get the DD Image by counterId") + // retrieving the Dd Image by counterId @GetMapping("/getImageByDdId") public ResponseEntity getImageByDdId(@RequestParam int counterId) { CounterDetails counterDetails = counterservice.getDdImageById(counterId); if (counterDetails != null) { - //System.out.println("CounterDetails found: " + counterDetails.getDdphoto()); + // System.out.println("CounterDetails found: " + counterDetails.getDdphoto()); return ResponseEntity.ok(counterDetails); } else { - //System.out.println("CounterDetails not found for ID: " + counterId); + // System.out.println("CounterDetails not found for ID: " + counterId); return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); } } - @Operation( - summary = "Counter Booking Cancellation by Letter and Reason REST API", - description = "REST API save the counter Booking Cancellation Letter and reason" - ) - //Saving the counter Booking Cancellation Letter and reason + @Operation(summary = "Counter Booking Cancellation by Letter and Reason REST API", description = "REST API save the counter Booking Cancellation Letter and reason") + // Saving the counter Booking Cancellation Letter and reason @PostMapping("/saveCancellation") public ResponseEntity saveCancellation( @RequestParam("counterId") int counterId, @RequestParam("uploadLetter") MultipartFile uploadLetter, @RequestParam("reason") String reason) throws IOException { - //System.out.println("Received counterId: " + counterId); - //System.out.println("Received file: " + uploadLetter.getOriginalFilename()); + // System.out.println("Received counterId: " + counterId); + // System.out.println("Received file: " + uploadLetter.getOriginalFilename()); // Fetch booking details using counterId List bookingList = bookingDetailsRepository.findByCounterId(counterId); if (bookingList.isEmpty()) { - //System.out.println("No bookings found for counterId: " + counterId); + // System.out.println("No bookings found for counterId: " + counterId); } for (BookingDetails booking : bookingList) { booking.setBookingStatus(BookingStatus.CANCELED); bookingDetailsRepository.save(booking); - List bookingCalendarList = bookingCalendarRepository.getCancellingdata1(String.valueOf(booking.getBookingId())); + List bookingCalendarList = bookingCalendarRepository + .getCancellingdata1(String.valueOf(booking.getBookingId())); for (BookingCalendar calendar : bookingCalendarList) { boolean isUpdated = false; @@ -900,32 +832,24 @@ public class UserAPIController { return ResponseEntity.ok(counterRefundList); } - - @Operation( - summary = "Counter Booking Details by CounterId REST API", - description = "REST API to get the Counter Details by CounterId" - ) - //retrieving Counter Booking Details by counterId + @Operation(summary = "Counter Booking Details by CounterId REST API", description = "REST API to get the Counter Details by CounterId") + // retrieving Counter Booking Details by counterId @GetMapping("/counterdetails") public List getUserDetailsbycounterId(@RequestParam("counterId") int counterId) { List counterRefundList = bookingDetailsRepository.getCounterDetailsbycounterId(counterId); return counterRefundList; } + // @GetMapping("/getUser") + // public ResponseEntity getUserByID(@RequestParam int userId){ + // if(userId == 0) { + // userId=userSession.getUserId(); + // } + // return ResponseEntity.ok(userService.getUserById(userId)); + // } -// @GetMapping("/getUser") -// public ResponseEntity getUserByID(@RequestParam int userId){ -// if(userId == 0) { -// userId=userSession.getUserId(); -// } -// return ResponseEntity.ok(userService.getUserById(userId)); -// } - - @Operation( - summary = "Updating the User Details Mobileno Validation REST API", - description = "REST API to Update the User Details if the User status is Rejected" - ) - //Updating the Rejected user details + @Operation(summary = "Updating the User Details Mobileno Validation REST API", description = "REST API to Update the User Details if the User status is Rejected") + // Updating the Rejected user details @PostMapping("/updateUserDetails") public String updateUserDetails( @RequestParam("userId") int userId, @@ -953,7 +877,8 @@ public class UserAPIController { // Handle profile photo if (profilephoto != null && !profilephoto.isEmpty()) { - //System.out.println("Profile photo uploaded: " + profilephoto.getOriginalFilename()); + // System.out.println("Profile photo uploaded: " + + // profilephoto.getOriginalFilename()); String fileName = userId + "_" + profilephoto.getOriginalFilename(); String filePath = "/images/userPhoto/" + fileName; File file = new File(uploadDirectory + "/userPhoto/" + fileName); @@ -980,18 +905,15 @@ public class UserAPIController { } - @Operation( - summary = "Counter User Details REST API", - description = "REST API to Get the User Details for Counter" - ) - //Retrive user details for counter + @Operation(summary = "Counter User Details REST API", description = "REST API to Get the User Details for Counter") + // Retrive user details for counter @GetMapping("/getuserforcounter") public ResponseEntity getCounterUserById(@RequestParam int userId) { if (userId == 0) { userId = userSession.getUserId(); // System.out.println("User ID retrieved from session: " + userId); } else { - //System.out.println("User ID provided as parameter: " + userId); + // System.out.println("User ID provided as parameter: " + userId); } Users user = userService.getUserById(userId); @@ -1001,11 +923,8 @@ public class UserAPIController { return ResponseEntity.ok(user); } - @Operation( - summary = "User Details REST API", - description = "REST API to Get the User Details" - ) - //retrieving User Details + @Operation(summary = "User Details REST API", description = "REST API to Get the User Details") + // retrieving User Details @GetMapping("/getUser") public ResponseEntity getUserByID(@RequestParam int userId) { if (userId == 0) { @@ -1035,16 +954,13 @@ public class UserAPIController { response.put("rejectionReason", rejectionReason); } - //System.out.println("Response: " + response); // Log the response + // System.out.println("Response: " + response); // Log the response return ResponseEntity.ok(response); } - @Operation( - summary = "Saving the Booking Details REST API", - description = "REST API to Save the Booking Details" - ) - //APi for Saving the Booking Details - @PostMapping(path = "/saveTheRequest2", consumes = {"multipart/form-data"}) + @Operation(summary = "Saving the Booking Details REST API", description = "REST API to Save the Booking Details") + // APi for Saving the Booking Details + @PostMapping(path = "/saveTheRequest2", consumes = { "multipart/form-data" }) public ResponseEntity saveTheBookingDetails2(HttpServletRequest request) { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; Map bookingDetails = splitFormData(multipartRequest); @@ -1078,26 +994,20 @@ public class UserAPIController { return formData; } - @Operation( - summary = "Retrieving the Booking Details by BookingId REST API", - description = "REST API to get the Booking Details by Booking Id" - ) - //retrieving the Booking Details BY Booking ID + @Operation(summary = "Retrieving the Booking Details by BookingId REST API", description = "REST API to get the Booking Details by Booking Id") + // retrieving the Booking Details BY Booking ID @GetMapping("/getBooking") public ResponseEntity getBookingByID(@RequestParam int bookingId) { return ResponseEntity.ok(bookingService.getBookingsById(bookingId)); } - @Operation( - summary = "User Booking Cancelling by BookingId REST API", - description = "REST API to Cancel the Booking by BookingId by User" - ) - //Booking Cancelling by BookingId -//Booking Cancelling by BookingId + @Operation(summary = "User Booking Cancelling by BookingId REST API", description = "REST API to Cancel the Booking by BookingId by User") + // Booking Cancelling by BookingId + // Booking Cancelling by BookingId @GetMapping("/cancelBookingbyId") public ResponseEntity cancelBooking(@RequestParam int bookingId, - @RequestParam BookingDetails.BookingStatus status, - @RequestParam String comments) { + @RequestParam BookingDetails.BookingStatus status, + @RequestParam String comments) { log.info("Received request to cancel booking with ID: {}"); log.info("Status: {}, Comments: {}"); Optional bookings = bookingDetailsRepository.findById(bookingId); @@ -1105,9 +1015,16 @@ public class UserAPIController { try { BookingDetails cancelledBooking = bookingService.updateCancelledBookingStatus(bookingId, status, comments); - String cancelledbookingsms = "Your booking ID " + bookingId + " on " + bookingDetails.getStartDate() + " has been cancelled successfully. The deposit amount will be refunded to your account within 3 to 15 days. Thanks for using the GCC Community Hall Booking System."; - String cancelledurlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + bookingDetails.getUsers().getMobileNo() + "&from=GCCCRP&body=" + cancelledbookingsms + "&entityid=1401572690000011081&templateid=1407172346829376988"; - String cancelledwhatsupmsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + bookingDetails.getUsers().getMobileNo() + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+booking+with+ID+" + bookingId + "+on+" + bookingDetails.getStartDate() + "+has+been+cancelled+successfully.+%0AThe+deposit+amount+will+be+refunded+to+your+account+within+3+to+15+days."; + String cancelledbookingsms = "Your booking ID " + bookingId + " on " + bookingDetails.getStartDate() + + " has been cancelled successfully. The deposit amount will be refunded to your account within 3 to 15 days. Thanks for using the GCC Community Hall Booking System."; + String cancelledurlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + + bookingDetails.getUsers().getMobileNo() + "&from=GCCCRP&body=" + cancelledbookingsms + + "&entityid=1401572690000011081&templateid=1407172346829376988"; + String cancelledwhatsupmsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + + bookingDetails.getUsers().getMobileNo() + + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+booking+with+ID+" + bookingId + + "+on+" + bookingDetails.getStartDate() + + "+has+been+cancelled+successfully.+%0AThe+deposit+amount+will+be+refunded+to+your+account+within+3+to+15+days."; whatsappMsgServiceImpl.sendMsg(cancelledwhatsupmsg); whatsappMsgServiceImpl.sendSMS(cancelledurlString); Optional book = bookingDetailsRepository.findById(bookingDetails.getBookingId()); @@ -1125,11 +1042,8 @@ public class UserAPIController { } } - @Operation( - summary = "Family Pensioner Details from ERP REST API", - description = "REST API to check the Family Pensioner Details From ERP" - ) - //checking Family pensioner Details + @Operation(summary = "Family Pensioner Details from ERP REST API", description = "REST API to check the Family Pensioner Details From ERP") + // checking Family pensioner Details @GetMapping("/FamilyPensionerDetails") @ResponseBody // Ensure Spring treats the returned object as the response body public Map getFamilyPensionerDetails(HttpServletRequest request, @RequestParam("id") Long id) { @@ -1156,10 +1070,11 @@ public class UserAPIController { .getFamilyPensionerDetails(); if (familyPensionerDetails != null && !familyPensionerDetails.isEmpty()) { - //Long mobileNo = Long.parseLong(familyPensionerDetailsResponse.getFamilyPensionerDetails().get(0).getMobile_no()); + // Long mobileNo = + // Long.parseLong(familyPensionerDetailsResponse.getFamilyPensionerDetails().get(0).getMobile_no()); Long mobileNo = 8220798937l; - //System.out.println("step 1"); + // System.out.println("step 1"); responseMap.put("mobileNo", mobileNo); } } @@ -1170,17 +1085,14 @@ public class UserAPIController { return responseMap; } - @Operation( - summary = "GCC Employee Details ERP REST API", - description = "REST API to retrieving the GCC Employee Details From ERP" - ) + @Operation(summary = "GCC Employee Details ERP REST API", description = "REST API to retrieving the GCC Employee Details From ERP") @GetMapping("/gccemployee") @ResponseBody // Ensure Spring treats the returned object as the response body public Map getGccEmployee(HttpServletRequest request, @RequestParam("id") Long id) { String purpose = "Checking GccEmployee"; RestTemplate restTemplate = new RestTemplate(); String url = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?serviceId=getEmployeeDetail&EmployeeID=" - + id; + + id + "&forCC=Yes"; ResponseEntity responseEntity = restTemplate.getForEntity(url, String.class); @@ -1200,10 +1112,11 @@ public class UserAPIController { .getEmployeeDetailsResult(); if (employeeDetails != null && !employeeDetails.isEmpty()) { - //Long mobileNo = Long.parseLong(familyPensionerDetailsResponse.getFamilyPensionerDetails().get(0).getMobile_no()); + // Long mobileNo = + // Long.parseLong(familyPensionerDetailsResponse.getFamilyPensionerDetails().get(0).getMobile_no()); - //Long mobileNo = 8220798933l; - //System.out.println("step 1"); + // Long mobileNo = 8220798933l; + // System.out.println("step 1"); responseMap.put("EmployeeDetailsResult", employeeDetails); } else { responseMap.put("EmployeeDetailsResult", null); @@ -1216,17 +1129,15 @@ public class UserAPIController { return responseMap; } - @Operation( - summary = "Pensioner Details ERP REST API", - description = "REST API to retrieving the Pensioner Details From ERP" - ) - //checking pensioner Details + @Operation(summary = "Pensioner Details ERP REST API", description = "REST API to retrieving the Pensioner Details From ERP") + // checking pensioner Details @GetMapping("/PensionerDetails") @ResponseBody public Map getPensionerDetails(HttpServletRequest request, @RequestParam("id") Long id) { String purpose = "Checking Employee"; RestTemplate restTemplate = new RestTemplate(); - String url = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?serviceId=getPensionerDetailsList&pensionerId=" + id; + String url = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?serviceId=getPensionerDetailsList&pensionerId=" + + id; ResponseEntity responseEntity = restTemplate.getForEntity(url, String.class); @@ -1238,14 +1149,15 @@ public class UserAPIController { Map responseMap = new HashMap<>(); try { - PensionerDetailsResponse pensionerDetailsResponse = objectMapper.readValue(jsonString, PensionerDetailsResponse.class); + PensionerDetailsResponse pensionerDetailsResponse = objectMapper.readValue(jsonString, + PensionerDetailsResponse.class); if (pensionerDetailsResponse != null) { List pensionerDetails = pensionerDetailsResponse.getEmployees(); if (pensionerDetails != null && !pensionerDetails.isEmpty()) { Long mobileNo = Long.parseLong(pensionerDetailsResponse.getEmployees().get(0).getMobile_no()); -// Long mobileNo = 9874561230l; + // Long mobileNo = 9874561230l; // System.out.println("step 2"); responseMap.put("mobileNo", mobileNo); return responseMap; @@ -1263,12 +1175,9 @@ public class UserAPIController { return responseMap; } - @Operation( - summary = "Saving Counter Details ERP REST API", - description = "REST API to save the Counter Details" - ) - //Saving the Counter Details - @PostMapping(path = "/counter-booking", consumes = {"multipart/form-data"}) + @Operation(summary = "Saving Counter Details ERP REST API", description = "REST API to save the Counter Details") + // Saving the Counter Details + @PostMapping(path = "/counter-booking", consumes = { "multipart/form-data" }) public ResponseEntity saveCounterBookingDetails(HttpServletRequest request) { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; Map bookingDetails = splitFormData(multipartRequest); @@ -1278,21 +1187,23 @@ public class UserAPIController { @GetMapping("/checkAvail") public List checkAvail(@RequestParam("fromDate") String fromDate, - @RequestParam("toDate") String toDate, - @RequestParam("starting") String starting, - @RequestParam("ending") String ending, - @RequestParam(name = "hallId", required = false) String hallId) { + @RequestParam("toDate") String toDate, + @RequestParam("starting") String starting, + @RequestParam("ending") String ending, + @RequestParam(name = "hallId", required = false) String hallId) { List data = new ArrayList<>(); HashSet removeHallId = new HashSet(); int hallIdd = 0; if (hallId != null && !hallId.equals("")) { hallIdd = Integer.parseInt(hallId); } - if (!fromDate.equals(toDate) && (starting.equals(ending) || starting.equals("evening") && ending.equals("morning"))) { + if (!fromDate.equals(toDate) + && (starting.equals(ending) || starting.equals("evening") && ending.equals("morning"))) { Map mp = incrementAndDecrementAndDaysCount(fromDate, toDate); long noOfDays = Long.parseLong(mp.get("NoOfDays").toString()); if (noOfDays > 2) { - data = calendarService.getCalendarByDateAndHallIdAndSlot(mp.get("fromDate"), mp.get("toDate"), starting, ending, hallIdd); + data = calendarService.getCalendarByDateAndHallIdAndSlot(mp.get("fromDate"), mp.get("toDate"), starting, + ending, hallIdd); for (int i = 0; i < data.size(); i++) { removeHallId.add(data.get(i).getHallId()); } @@ -1300,32 +1211,36 @@ public class UserAPIController { } data = calendarService.getCalendarByDateAndHallIdAndSlot(fromDate, toDate, starting, ending, hallIdd); - //System.out.println("data size :-"+data.size()); + // System.out.println("data size :-"+data.size()); if (starting != null && ending != null) { boolean checkAvail = false; int checkHallId = 0; for (int i = 0; i < data.size(); i++) { - if ((starting.equals("evening") || ending.equals("morning")) && fromDate.equals(data.get(i).getBdate().toString()) && toDate.equals(fromDate)) { + if ((starting.equals("evening") || ending.equals("morning")) + && fromDate.equals(data.get(i).getBdate().toString()) && toDate.equals(fromDate)) { if (data.get(i).isEveningSlot() == false) { continue; } else if (data.get(i).isMorningSlot() == false) { continue; } - } else if ((starting.equals(ending) || starting.equals("evening") && ending.equals("morning")) && !toDate.equals(fromDate)) { + } else if ((starting.equals(ending) || starting.equals("evening") && ending.equals("morning")) + && !toDate.equals(fromDate)) { if (checkHallId == 0 || checkHallId != data.get(i).getHallId()) { checkHallId = data.get(i).getHallId(); checkAvail = false; } if (starting.equals("morning") && ending.equals("morning")) { - if (fromDate.equals(data.get(i).getBdate().toString()) && data.get(i).isMorningSlot() == false) { + if (fromDate.equals(data.get(i).getBdate().toString()) + && data.get(i).isMorningSlot() == false) { if (checkHallId == data.get(i).getHallId()) { continue; } - } else if (toDate.equals(data.get(i).getBdate().toString()) && data.get(i).isMorningSlot() == false) { + } else if (toDate.equals(data.get(i).getBdate().toString()) + && data.get(i).isMorningSlot() == false) { if (checkHallId == data.get(i).getHallId() && checkAvail == false) { checkHallId = data.get(i).getHallId(); continue; @@ -1333,22 +1248,26 @@ public class UserAPIController { } } else if (starting.equals("evening") && ending.equals("morning")) { - if (fromDate.equals(data.get(i).getBdate().toString()) && data.get(i).isEveningSlot() == false) { + if (fromDate.equals(data.get(i).getBdate().toString()) + && data.get(i).isEveningSlot() == false) { if (checkHallId == data.get(i).getHallId()) { continue; } - } else if (toDate.equals(data.get(i).getBdate().toString()) && data.get(i).isMorningSlot() == false) { + } else if (toDate.equals(data.get(i).getBdate().toString()) + && data.get(i).isMorningSlot() == false) { if (checkHallId == data.get(i).getHallId() && checkAvail == false) { checkHallId = data.get(i).getHallId(); continue; } } } else if (starting.equals("evening") && ending.equals("evening")) { - if (fromDate.equals(data.get(i).getBdate().toString()) && data.get(i).isEveningSlot() == false) { + if (fromDate.equals(data.get(i).getBdate().toString()) + && data.get(i).isEveningSlot() == false) { if (checkHallId == data.get(i).getHallId()) { continue; } - } else if (toDate.equals(data.get(i).getBdate().toString()) && data.get(i).isEveningSlot() == false) { + } else if (toDate.equals(data.get(i).getBdate().toString()) + && data.get(i).isEveningSlot() == false) { if (checkHallId == data.get(i).getHallId() && checkAvail == false) { checkHallId = data.get(i).getHallId(); continue; @@ -1360,7 +1279,7 @@ public class UserAPIController { } } } - //System.out.println(data.get(i).getHallId()); + // System.out.println(data.get(i).getHallId()); removeHallId.add(data.get(i).getHallId()); } } @@ -1405,7 +1324,7 @@ public class UserAPIController { } - //Reschedule + // Reschedule @PostMapping("/reschedule-dates") public ResponseEntity updateBookingDates( @RequestParam int bookingId, @@ -1444,7 +1363,8 @@ public class UserAPIController { Map paymentDetail = new HashMap<>(); paymentDetail.put("status", "PAYMENT_SUCCESS"); paymentDetail.put("description", "Payment Success"); - paymentDetail.put("dateTime", bookingDetails.getPayments().getCdate()); // Assuming Cdate is the created date + paymentDetail.put("dateTime", bookingDetails.getPayments().getCdate()); // Assuming Cdate is the created + // date trackingDetails.add(paymentDetail); } @@ -1453,7 +1373,8 @@ public class UserAPIController { Map bookingApprovedDetail = new HashMap<>(); bookingApprovedDetail.put("status", "APPROVED"); bookingApprovedDetail.put("description", "Booking Approved"); - bookingApprovedDetail.put("dateTime", bookingDetails.getBookingDate()); // Assuming BookingDate is correct + bookingApprovedDetail.put("dateTime", bookingDetails.getBookingDate()); // Assuming BookingDate is + // correct trackingDetails.add(bookingApprovedDetail); } @@ -1501,22 +1422,22 @@ public class UserAPIController { trackingDetails.add(refundCompletedDetail); } - if (bookingDetails.getBookingStatus() == BookingStatus.CANCELED) { Map bookingCanceledDetail = new HashMap<>(); bookingCanceledDetail.put("status", "CANCELED"); bookingCanceledDetail.put("description", "Booking Cancelled"); - bookingCanceledDetail.put("dateTime", bookingDetails.getUpdatedDate()); // Assuming BookingDate is correct + bookingCanceledDetail.put("dateTime", bookingDetails.getUpdatedDate()); // Assuming BookingDate is + // correct trackingDetails.add(bookingCanceledDetail); } - if (bookingDetails.getBookingStatus() == BookingStatus.CANCELED && bookingDetails.getRefundStatus() == RefundStatus.WAITING) { Map canceledRaisingDetail = new HashMap<>(); canceledRaisingDetail.put("status", "SETTLEMENT_RAISING"); canceledRaisingDetail.put("description", "Settlement Raising"); - canceledRaisingDetail.put("dateTime", bookingDetails.getUpdatedDate()); // Assuming BookingDate is correct + canceledRaisingDetail.put("dateTime", bookingDetails.getUpdatedDate()); // Assuming BookingDate is + // correct trackingDetails.add(canceledRaisingDetail); } @@ -1533,17 +1454,18 @@ public class UserAPIController { Map bookingRejectedDetail = new HashMap<>(); bookingRejectedDetail.put("status", "REJECTED"); bookingRejectedDetail.put("description", "Booking Rejected"); - bookingRejectedDetail.put("dateTime", bookingDetails.getUpdatedDate()); // Assuming BookingDate is correct + bookingRejectedDetail.put("dateTime", bookingDetails.getUpdatedDate()); // Assuming BookingDate is + // correct trackingDetails.add(bookingRejectedDetail); } - if (bookingDetails.getBookingStatus() == BookingStatus.REJECTED && bookingDetails.getRefundStatus() == RefundStatus.WAITING) { Map rejectedRaisingDetail = new HashMap<>(); rejectedRaisingDetail.put("status", "SETTLEMENT_RAISING"); rejectedRaisingDetail.put("description", "Settlement Raising"); - rejectedRaisingDetail.put("dateTime", bookingDetails.getUpdatedDate()); // Assuming BookingDate is correct + rejectedRaisingDetail.put("dateTime", bookingDetails.getUpdatedDate()); // Assuming BookingDate is + // correct trackingDetails.add(rejectedRaisingDetail); } @@ -1556,7 +1478,6 @@ public class UserAPIController { trackingDetails.add(rejectedRefundCompletedDetail); } - if (bookingDetails.getBookingStatus() == BookingStatus.GCC_BLOCKED) { Map gccBlockedDetail = new HashMap<>(); gccBlockedDetail.put("status", "GCC_BLOCKED"); @@ -1568,7 +1489,6 @@ public class UserAPIController { return trackingDetails; } - @GetMapping("/confirmstatebooking") public String Confirmstatebookig(@RequestParam int bookingId) { String response = bookingService.confirmStateBooking(bookingId); @@ -1577,136 +1497,162 @@ public class UserAPIController { @PostMapping("/uploaddocs") public ResponseEntity uploadDocs(@RequestParam("nocFile") MultipartFile file, - @RequestParam("bookingssId") int bookingId) { + @RequestParam("bookingssId") int bookingId) { try { bookingService.uploadNOCFile(file, bookingId); return ResponseEntity.ok("File uploaded and saved successfully"); } catch (Exception e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("File upload failed: " + e.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body("File upload failed: " + e.getMessage()); } } - /*@GetMapping("/calculatehallamount") - public ResponseEntity> getHallDetailsConcession( - @RequestParam int numDays, - @RequestParam(value = "startPeriod", required = false) String startPeriod, - @RequestParam(value = "endPeriod", required = false) String endPeriod, - @RequestParam(value = "reasonforBooking", required = false) String reasonforBooking, - @RequestParam int hallId) { - - Optional hallDetailsOpt = hallDetailsRepository.findById(hallId); - - if (!hallDetailsOpt.isPresent()) { - return ResponseEntity.status(404).body(null); // Handle not found - } - - HallDetails hallDetails = hallDetailsOpt.get(); - boolean isSGE = hallDetails.isSGE(); - boolean isCGE = hallDetails.isCGE(); - - double fullDayAmount = hallDetails.getFullDayRent(); - double halfDayAmount = hallDetails.getHalfDayRent(); - double depositAmount = hallDetails.getDepositAmount(); - double gstRate = hallDetails.getGst(); - - Map response = new HashMap<>(); - - double amount = calculateAmount(numDays, startPeriod, endPeriod, fullDayAmount, halfDayAmount); - double totalDepositAmount = depositAmount * numDays; - double totalAmount; - double discountAmount = 0.0; - response.put("reasonforBooking", reasonforBooking); - - if (!isSGE) { - totalAmount = amount + (amount * gstRate / 100) + totalDepositAmount; - response.put("discount", 0); - response.put("amount", amount); - response.put("totalAmount", totalAmount); - response.put("depositAmount", totalDepositAmount); - double gstValue =gstRate * amount / 100.0; - response.put("gst", gstValue); - response.put("discountAmount", amount); - } else { - if ("SGE".equals(reasonforBooking)) { - double cleaningCharges = hallDetails.getHallDetailsConcession().get(0).getFullDayCleaningcharges(); - double pasystem=hallDetails.getHallDetailsConcession().get(0).getFulldayPAsystem(); - double ebCharges=hallDetails.getHallDetailsConcession().get(0).getFulldayEBcharges(); - double halfcleaningCharges = hallDetails.getHallDetailsConcession().get(0).getHalfDayCleaningcharges(); - double halfpasystem=hallDetails.getHallDetailsConcession().get(0).getHalfdayPAsystem(); - double halfebCharges=hallDetails.getHallDetailsConcession().get(0).getHalfdayEBcharges(); - double fulladditionalCharges = cleaningCharges+pasystem+ebCharges; - double halfadditionalCharges = halfcleaningCharges+halfpasystem+halfebCharges; - double fulldayhallAmount=hallDetails.getHallDetailsConcession().get(0).getFulldayhallamount(); - double halfdayhallAmount=hallDetails.getHallDetailsConcession().get(0).getHalfdayhallamount(); - double additionalCharges=calculateAmount(numDays, startPeriod, endPeriod, fulladditionalCharges, halfadditionalCharges); - totalAmount = additionalCharges + totalDepositAmount + (additionalCharges * gstRate / 100.0); - discountAmount = (fulldayhallAmount * hallDetails.getSGEdiscount()) / 100.0; - response.put("startperiod", startPeriod); - response.put("endPeriod", endPeriod); - response.put("fulldayhallAmount", fulldayhallAmount); - response.put("halfdayhallAmount", halfdayhallAmount); - response.put("discount", hallDetails.getSGEdiscount()); - response.put("rentAmount", 0); - response.put("additionalCharges", additionalCharges); - response.put("netAmount", additionalCharges); - response.put("gst", gstRate * additionalCharges / 100); - response.put("depositAmount", totalDepositAmount); - response.put("totalAmount", totalAmount); - response.put("discountAmount", discountAmount); - } else if ("CGE".equals(reasonforBooking)) { - response.put("discount", hallDetails.getCGEdiscount()); - discountAmount = (amount * hallDetails.getCGEdiscount()) / 100.0; - totalAmount = discountAmount + totalDepositAmount + (discountAmount * gstRate / 100); - response.put("amount", amount); - response.put("totalAmount", totalAmount); - response.put("depositAmount", totalDepositAmount); - double gstValue = gstRate * discountAmount / 100; - response.put("gst", gstValue); - response.put("discountAmount", discountAmount); - } else { - totalAmount = amount + (amount * gstRate / 100) + totalDepositAmount; - response.put("discount", 0); - response.put("amount", amount); - response.put("totalAmount", totalAmount); - response.put("depositAmount", totalDepositAmount); - double gstValue =gstRate * amount / 100.0; - response.put("gst", gstValue); - response.put("discountAmount", amount); - } - } - - return ResponseEntity.ok(response); - } - public double calculateAmount(double numDays, String startPeriod, String endPeriod, double fullDayAmount, double halfDayAmount) { - double amount = 0; - - // If there is only one day - if (numDays == 1) { - if ("1".equals(startPeriod) && "2".equals(endPeriod)) { - amount = fullDayAmount; - } else if ("1".equals(startPeriod) && "1".equals(endPeriod)) { - amount = halfDayAmount; - } else if ("2".equals(startPeriod) && "2".equals(endPeriod)) { - amount = halfDayAmount; - }else { - amount=numDays; - } - } else { - // For multiple days - if ("1".equals(startPeriod) && "2".equals(endPeriod)) { - amount = fullDayAmount * numDays; - } else if ("1".equals(startPeriod) && "1".equals(endPeriod)) { - amount = fullDayAmount * (numDays - 1) + halfDayAmount; - } else if ("2".equals(startPeriod) && "2".equals(endPeriod)) { - amount = fullDayAmount * (numDays - 1) + halfDayAmount; - } else if ("2".equals(startPeriod) && "1".equals(endPeriod)) { - amount = fullDayAmount * (numDays - 2) + halfDayAmount * 2; - }else { - amount=numDays; - } - } - - return amount; - }*/ + /* + * @GetMapping("/calculatehallamount") + * public ResponseEntity> getHallDetailsConcession( + * + * @RequestParam int numDays, + * + * @RequestParam(value = "startPeriod", required = false) String startPeriod, + * + * @RequestParam(value = "endPeriod", required = false) String endPeriod, + * + * @RequestParam(value = "reasonforBooking", required = false) String + * reasonforBooking, + * + * @RequestParam int hallId) { + * + * Optional hallDetailsOpt = + * hallDetailsRepository.findById(hallId); + * + * if (!hallDetailsOpt.isPresent()) { + * return ResponseEntity.status(404).body(null); // Handle not found + * } + * + * HallDetails hallDetails = hallDetailsOpt.get(); + * boolean isSGE = hallDetails.isSGE(); + * boolean isCGE = hallDetails.isCGE(); + * + * double fullDayAmount = hallDetails.getFullDayRent(); + * double halfDayAmount = hallDetails.getHalfDayRent(); + * double depositAmount = hallDetails.getDepositAmount(); + * double gstRate = hallDetails.getGst(); + * + * Map response = new HashMap<>(); + * + * double amount = calculateAmount(numDays, startPeriod, endPeriod, + * fullDayAmount, halfDayAmount); + * double totalDepositAmount = depositAmount * numDays; + * double totalAmount; + * double discountAmount = 0.0; + * response.put("reasonforBooking", reasonforBooking); + * + * if (!isSGE) { + * totalAmount = amount + (amount * gstRate / 100) + totalDepositAmount; + * response.put("discount", 0); + * response.put("amount", amount); + * response.put("totalAmount", totalAmount); + * response.put("depositAmount", totalDepositAmount); + * double gstValue =gstRate * amount / 100.0; + * response.put("gst", gstValue); + * response.put("discountAmount", amount); + * } else { + * if ("SGE".equals(reasonforBooking)) { + * double cleaningCharges = + * hallDetails.getHallDetailsConcession().get(0).getFullDayCleaningcharges(); + * double + * pasystem=hallDetails.getHallDetailsConcession().get(0).getFulldayPAsystem(); + * double + * ebCharges=hallDetails.getHallDetailsConcession().get(0).getFulldayEBcharges() + * ; + * double halfcleaningCharges = + * hallDetails.getHallDetailsConcession().get(0).getHalfDayCleaningcharges(); + * double + * halfpasystem=hallDetails.getHallDetailsConcession().get(0).getHalfdayPAsystem + * (); + * double halfebCharges=hallDetails.getHallDetailsConcession().get(0). + * getHalfdayEBcharges(); + * double fulladditionalCharges = cleaningCharges+pasystem+ebCharges; + * double halfadditionalCharges = + * halfcleaningCharges+halfpasystem+halfebCharges; + * double fulldayhallAmount=hallDetails.getHallDetailsConcession().get(0). + * getFulldayhallamount(); + * double halfdayhallAmount=hallDetails.getHallDetailsConcession().get(0). + * getHalfdayhallamount(); + * double additionalCharges=calculateAmount(numDays, startPeriod, endPeriod, + * fulladditionalCharges, halfadditionalCharges); + * totalAmount = additionalCharges + totalDepositAmount + (additionalCharges * + * gstRate / 100.0); + * discountAmount = (fulldayhallAmount * hallDetails.getSGEdiscount()) / 100.0; + * response.put("startperiod", startPeriod); + * response.put("endPeriod", endPeriod); + * response.put("fulldayhallAmount", fulldayhallAmount); + * response.put("halfdayhallAmount", halfdayhallAmount); + * response.put("discount", hallDetails.getSGEdiscount()); + * response.put("rentAmount", 0); + * response.put("additionalCharges", additionalCharges); + * response.put("netAmount", additionalCharges); + * response.put("gst", gstRate * additionalCharges / 100); + * response.put("depositAmount", totalDepositAmount); + * response.put("totalAmount", totalAmount); + * response.put("discountAmount", discountAmount); + * } else if ("CGE".equals(reasonforBooking)) { + * response.put("discount", hallDetails.getCGEdiscount()); + * discountAmount = (amount * hallDetails.getCGEdiscount()) / 100.0; + * totalAmount = discountAmount + totalDepositAmount + (discountAmount * gstRate + * / 100); + * response.put("amount", amount); + * response.put("totalAmount", totalAmount); + * response.put("depositAmount", totalDepositAmount); + * double gstValue = gstRate * discountAmount / 100; + * response.put("gst", gstValue); + * response.put("discountAmount", discountAmount); + * } else { + * totalAmount = amount + (amount * gstRate / 100) + totalDepositAmount; + * response.put("discount", 0); + * response.put("amount", amount); + * response.put("totalAmount", totalAmount); + * response.put("depositAmount", totalDepositAmount); + * double gstValue =gstRate * amount / 100.0; + * response.put("gst", gstValue); + * response.put("discountAmount", amount); + * } + * } + * + * return ResponseEntity.ok(response); + * } + * public double calculateAmount(double numDays, String startPeriod, String + * endPeriod, double fullDayAmount, double halfDayAmount) { + * double amount = 0; + * + * // If there is only one day + * if (numDays == 1) { + * if ("1".equals(startPeriod) && "2".equals(endPeriod)) { + * amount = fullDayAmount; + * } else if ("1".equals(startPeriod) && "1".equals(endPeriod)) { + * amount = halfDayAmount; + * } else if ("2".equals(startPeriod) && "2".equals(endPeriod)) { + * amount = halfDayAmount; + * }else { + * amount=numDays; + * } + * } else { + * // For multiple days + * if ("1".equals(startPeriod) && "2".equals(endPeriod)) { + * amount = fullDayAmount * numDays; + * } else if ("1".equals(startPeriod) && "1".equals(endPeriod)) { + * amount = fullDayAmount * (numDays - 1) + halfDayAmount; + * } else if ("2".equals(startPeriod) && "2".equals(endPeriod)) { + * amount = fullDayAmount * (numDays - 1) + halfDayAmount; + * } else if ("2".equals(startPeriod) && "1".equals(endPeriod)) { + * amount = fullDayAmount * (numDays - 2) + halfDayAmount * 2; + * }else { + * amount=numDays; + * } + * } + * + * return amount; + * } + */ @GetMapping("/calculatehallamount") public ResponseEntity> getHallDetailsConcession( @@ -1735,7 +1681,8 @@ public class UserAPIController { Map response = new HashMap<>(); double amount = calculateAmount(numDays, startPeriod, endPeriod, fullDayAmount, halfDayAmount); - double totalDepositAmount = calculateDepositAmount(numDays, startPeriod, endPeriod, depositAmount, halfDepositAmount); + double totalDepositAmount = calculateDepositAmount(numDays, startPeriod, endPeriod, depositAmount, + halfDepositAmount); double totalAmount; double discountAmount = 0.0; response.put("reasonforBooking", reasonforBooking); @@ -1761,7 +1708,8 @@ public class UserAPIController { double halfadditionalCharges = halfcleaningCharges + halfpasystem + halfebCharges; double fulldayhallAmount = hallDetails.getHallDetailsConcession().get(0).getFulldayhallamount(); double halfdayhallAmount = hallDetails.getHallDetailsConcession().get(0).getHalfdayhallamount(); - double additionalCharges = calculateAmount(numDays, startPeriod, endPeriod, fulladditionalCharges, halfadditionalCharges); + double additionalCharges = calculateAmount(numDays, startPeriod, endPeriod, fulladditionalCharges, + halfadditionalCharges); totalAmount = additionalCharges + totalDepositAmount + (additionalCharges * gstRate / 100.0); discountAmount = (fulldayhallAmount * hallDetails.getSGEdiscount()) / 100.0; response.put("startperiod", startPeriod); @@ -1785,7 +1733,8 @@ public class UserAPIController { double halfebCharges = hallDetails.getHallDetailsConcession().get(0).getHalfdayEBcharges(); double fulladditionalCharges = cleaningCharges + pasystem + ebCharges; double halfadditionalCharges = halfcleaningCharges + halfpasystem + halfebCharges; - double additionalCharges = calculateAmount(numDays, startPeriod, endPeriod, fulladditionalCharges, halfadditionalCharges); + double additionalCharges = calculateAmount(numDays, startPeriod, endPeriod, fulladditionalCharges, + halfadditionalCharges); double rentAmount = (amount * hallDetails.getCGEdiscount()) / 100.0; double netAmount = rentAmount + additionalCharges; double gst = ((additionalCharges + rentAmount) * gstRate / 100.0); @@ -1817,7 +1766,8 @@ public class UserAPIController { return ResponseEntity.ok(response); } - public double calculateAmount(double numDays, String startPeriod, String endPeriod, double fullDayAmount, double halfDayAmount) { + public double calculateAmount(double numDays, String startPeriod, String endPeriod, double fullDayAmount, + double halfDayAmount) { double amount = 0; // If there is only one day @@ -1867,7 +1817,6 @@ public class UserAPIController { return response; } - @GetMapping("/collectionpendingacknowledgementsss") public BookingDetails viewCollectionpendingAck(Model model, int bookingId) { BookingDetails bookingsDetails = bookingService.getBookingsById(bookingId); @@ -1888,9 +1837,10 @@ public class UserAPIController { } } - public double calculateDepositAmount(double numDays, String startPeriod, String endPeriod, double depositAmount, double HalfDepositAmount) { + public double calculateDepositAmount(double numDays, String startPeriod, String endPeriod, double depositAmount, + double HalfDepositAmount) { double damount = 0; - // FOR FULL DAY + // FOR FULL DAY // If there is only one day if (numDays == 1) { if ("1".equals(startPeriod) && "2".equals(endPeriod)) { @@ -1919,6 +1869,4 @@ public class UserAPIController { return damount; } - } - diff --git a/src/main/java/com/gcc/communityHall/controller/UserController.java b/src/main/java/com/gcc/communityHall/controller/UserController.java index 66464c01..52cf0dc2 100644 --- a/src/main/java/com/gcc/communityHall/controller/UserController.java +++ b/src/main/java/com/gcc/communityHall/controller/UserController.java @@ -2,6 +2,7 @@ package com.gcc.communityHall.controller; import java.time.LocalDate; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -350,31 +351,63 @@ public class UserController { @RequestParam(name = "bookingStatus", required = false) String bookingStatus) { Integer userId = userSession.getUserId(); + // Extract booking_ref_id per booking + Map refIdMap = new HashMap<>(); model.addAttribute("userName", userSession.getDispayName()); model.addAttribute("counter", userSession.getCounter()); model.addAttribute("counterName", userSession.getCounterName()); // Fetch all past bookings + // List> bookingPast = + // bookingService.getAllBookingEventsByUserId(userId); + + // if (!bookingPast.isEmpty() || bookingPast.size() == 0) { + + // for (Map row : bookingPast) { + + // Integer bookingId = (Integer) row.get("booking_id"); + // String refId = (String) row.get("booking_ref_id"); // <-- coming from SQL + + // if (bookingId != null && refId != null) { + // refIdMap.put(bookingId, refId); + // } + // } + // System.out.println("Row keys: " + bookingPast.get(0).keySet()); + // System.out.println("RefId Map123: " + refIdMap); + // } + + // model.addAttribute("userBookingspast", bookingPast); + // model.addAttribute("bookingRefIds", refIdMap); // <-- SENT TO FRONTEND + // model.addAttribute("serverDate", LocalDate.now().toString()); + List> bookingPast = bookingService.getAllBookingEventsByUserId(userId); - // Extract booking_ref_id per booking - Map refIdMap = new HashMap<>(); + if (bookingPast != null && !bookingPast.isEmpty()) { + + for (Map row : bookingPast) { - for (Map row : bookingPast) { + Integer bookingId = row.get("booking_id") != null + ? ((Number) row.get("booking_id")).intValue() + : null; - Integer bookingId = (Integer) row.get("booking_id"); - String refId = (String) row.get("booking_ref_id"); // <-- coming from SQL + String refId = row.get("booking_ref_id") != null + ? row.get("booking_ref_id").toString() + : null; - if (bookingId != null && refId != null) { - refIdMap.put(bookingId, refId); + if (bookingId != null && refId != null) { + refIdMap.put(bookingId, refId); + } } + + System.out.println("Row keys: " + bookingPast.get(0).keySet()); + System.out.println("RefId Map: " + refIdMap); + } else { + System.out.println("No past bookings found for userId: " + userId); } - System.out.println("Row keys: " + bookingPast.get(0).keySet()); - System.out.println("RefId Map123: " + refIdMap); - model.addAttribute("userBookingspast", bookingPast); - model.addAttribute("bookingRefIds", refIdMap); // <-- SENT TO FRONTEND + model.addAttribute("userBookingspast", bookingPast != null ? bookingPast : Collections.emptyList()); + model.addAttribute("bookingRefIds", refIdMap); model.addAttribute("serverDate", LocalDate.now().toString()); return "user/viewhistory"; diff --git a/src/main/java/com/gcc/communityHall/dto/EmployeeDetails.java b/src/main/java/com/gcc/communityHall/dto/EmployeeDetails.java index 20ee2b4d..3e5d27aa 100644 --- a/src/main/java/com/gcc/communityHall/dto/EmployeeDetails.java +++ b/src/main/java/com/gcc/communityHall/dto/EmployeeDetails.java @@ -13,6 +13,12 @@ public class EmployeeDetails { @JsonProperty("Designation") private String Designation; + @JsonProperty("Code") + private String Code; + + @JsonProperty("RetirementDate") + private String RetirementDate; + public String getName() { return name; } @@ -37,6 +43,22 @@ public class EmployeeDetails { Designation = designation; } + public String getCode() { + return Code; + } + + public void setCode(String code) { + Designation = code; + } + + public String getRetirmentDate() { + return RetirementDate; + } + + public void setRetirementDate(String retirementDate) { + RetirementDate = retirementDate; + } + } diff --git a/src/main/java/com/gcc/communityHall/entity/HallDetails.java b/src/main/java/com/gcc/communityHall/entity/HallDetails.java index 92fb6730..bd32cb8c 100644 --- a/src/main/java/com/gcc/communityHall/entity/HallDetails.java +++ b/src/main/java/com/gcc/communityHall/entity/HallDetails.java @@ -4,6 +4,8 @@ import java.time.LocalDate; import java.util.Date; import java.util.List; +import com.fasterxml.jackson.annotation.JsonIgnore; + import jakarta.persistence.CascadeType; import jakarta.persistence.Column; import jakarta.persistence.Entity; @@ -27,31 +29,31 @@ public class HallDetails { private int pinCode; private String division; private String zone; - @Column(name="land_mark") + @Column(name = "land_mark") private String landMark; - @Column(name="latitude") + @Column(name = "latitude") private String latitude; - @Column(name="longitude") + @Column(name = "longitude") private String longitude; private float hallArea; - @Column(name="seating_capacity") + @Column(name = "seating_capacity") private int seatingCapacity; - @Column(name="parking_capacity") + @Column(name = "parking_capacity") private String parkingCapacity; - @OneToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER,mappedBy = "hallDetails") + @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "hallDetails") private List hallImagesList; - - @OneToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER,mappedBy = "hallDetails") + + @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "hallDetails") private List floorDetailsList; - - @OneToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER,mappedBy = "hallDetails") + + @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "hallDetails") private List hallDetailsConcession; - - @Column(name="hall_Incharge_no",nullable=false) + + @Column(name = "hall_Incharge_no", nullable = false) private long hallInchargeMobno; - @Column(name="hall_Incharge_name",nullable=false) + @Column(name = "hall_Incharge_name", nullable = false) private String hallInchargeName; @Column(name = "deposit_amount", nullable = false) @@ -60,31 +62,54 @@ public class HallDetails { @Column(name = "half_deposit_amount", nullable = false) private float halfDepositAmount; - @Column(name="full_day_rent",nullable=false) + @Column(name = "full_day_rent", nullable = false) private float fullDayRent; - @Column(name="half_day_rent",nullable=false) + @Column(name = "half_day_rent", nullable = false) private float halfDayRent; private float gst; - @Column(nullable = false,columnDefinition = "BOOLEAN DEFAULT true") - private boolean isActive =true; - @Column(nullable = false,columnDefinition = "BOOLEAN DEFAULT false") - private boolean isDelete =false; - @Column(name="c_date") + @Column(nullable = false, columnDefinition = "BOOLEAN DEFAULT true") + private boolean isActive = true; + @Column(nullable = false, columnDefinition = "BOOLEAN DEFAULT false") + private boolean isDelete = false; + @Column(name = "c_date") private LocalDate createddate; - @Column(name=" updated_id") + @Column(name = " updated_id") private String updatedId; - @Column(name="update_date") + @Column(name = "update_date") private Date updatedDate = new Date(); private String ebNumber; private float ebCostPerUnit; private String city; - @Column(nullable = false,columnDefinition = "BOOLEAN DEFAULT false") - private boolean SGE=false; - @Column(nullable = false,columnDefinition = "BOOLEAN DEFAULT false") - private boolean CGE=false; + @Column(nullable = false, columnDefinition = "BOOLEAN DEFAULT false") + private boolean SGE = false; + @Column(nullable = false, columnDefinition = "BOOLEAN DEFAULT false") + private boolean CGE = false; private float SGEdiscount; private float CGEdiscount; + @Column(name = "is_reason_restricted", nullable = false, columnDefinition = "BOOLEAN DEFAULT false") + private boolean isReasonRestricted = false; + + @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "hallDetails") + @JsonIgnore + private List hallReasonRestrictions; + + public boolean isReasonRestricted() { + return isReasonRestricted; + } + + public void setReasonRestricted(boolean isReasonRestricted) { + this.isReasonRestricted = isReasonRestricted; + } + + public List getHallReasonRestrictions() { + return hallReasonRestrictions; + } + + public void setHallReasonRestrictions(List hallReasonRestrictions) { + this.hallReasonRestrictions = hallReasonRestrictions; + } + public int getHallId() { return hallId; } @@ -254,22 +279,22 @@ public class HallDetails { } public boolean isActive() { - return isActive; - } + return isActive; + } - public void setActive(boolean isActive) { - this.isActive = isActive; - } + public void setActive(boolean isActive) { + this.isActive = isActive; + } - public boolean isDelete() { - return isDelete; - } + public boolean isDelete() { + return isDelete; + } - public void setDelete(boolean isDelete) { - this.isDelete = isDelete; - } + public void setDelete(boolean isDelete) { + this.isDelete = isDelete; + } - public LocalDate getCreateddate() { + public LocalDate getCreateddate() { return createddate; } @@ -321,53 +346,53 @@ public class HallDetails { this.ebCostPerUnit = ebCostPerUnit; } - public List getFloorDetailsList() { - return floorDetailsList; - } + public List getFloorDetailsList() { + return floorDetailsList; + } - public void setFloorDetailsList(List floorDetailsList) { - this.floorDetailsList = floorDetailsList; - } + public void setFloorDetailsList(List floorDetailsList) { + this.floorDetailsList = floorDetailsList; + } - public boolean isSGE() { - return SGE; - } + public boolean isSGE() { + return SGE; + } - public void setSGE(boolean sGE) { - SGE = sGE; - } + public void setSGE(boolean sGE) { + SGE = sGE; + } - public boolean isCGE() { - return CGE; - } + public boolean isCGE() { + return CGE; + } - public void setCGE(boolean cGE) { - CGE = cGE; - } + public void setCGE(boolean cGE) { + CGE = cGE; + } - public float getSGEdiscount() { - return SGEdiscount; - } + public float getSGEdiscount() { + return SGEdiscount; + } - public void setSGEdiscount(float sGEdiscount) { - SGEdiscount = sGEdiscount; - } + public void setSGEdiscount(float sGEdiscount) { + SGEdiscount = sGEdiscount; + } - public float getCGEdiscount() { - return CGEdiscount; - } + public float getCGEdiscount() { + return CGEdiscount; + } - public void setCGEdiscount(float cGEdiscount) { - CGEdiscount = cGEdiscount; - } + public void setCGEdiscount(float cGEdiscount) { + CGEdiscount = cGEdiscount; + } - public List getHallDetailsConcession() { - return hallDetailsConcession; - } + public List getHallDetailsConcession() { + return hallDetailsConcession; + } - public void setHallDetailsConcession(List hallDetailsConcession) { - this.hallDetailsConcession = hallDetailsConcession; - } + public void setHallDetailsConcession(List hallDetailsConcession) { + this.hallDetailsConcession = hallDetailsConcession; + } public float getHalfDepositAmount() { return halfDepositAmount; @@ -376,5 +401,5 @@ public class HallDetails { public void setHalfDepositAmount(float halfDepositAmount) { this.halfDepositAmount = halfDepositAmount; } - + } diff --git a/src/main/java/com/gcc/communityHall/entity/HallReasonRestriction.java b/src/main/java/com/gcc/communityHall/entity/HallReasonRestriction.java new file mode 100644 index 00000000..2e388094 --- /dev/null +++ b/src/main/java/com/gcc/communityHall/entity/HallReasonRestriction.java @@ -0,0 +1,68 @@ +package com.gcc.communityHall.entity; + +import java.time.LocalDate; + +import com.fasterxml.jackson.annotation.JsonIgnore; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; + +@Entity +@Table(name = "hall_reason_restriction") +public class HallReasonRestriction { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private int id; + + @ManyToOne(fetch = FetchType.EAGER) + @JoinColumn(name = "hall_id", nullable = false) + @JsonIgnore + private HallDetails hallDetails; + + @ManyToOne(fetch = FetchType.EAGER) + @JoinColumn(name = "reason_id", nullable = false) + private ReasonMaster reasonMaster; + + @Column(name = "created_date") + private LocalDate createdDate = LocalDate.now(); + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public HallDetails getHallDetails() { + return hallDetails; + } + + public void setHallDetails(HallDetails hallDetails) { + this.hallDetails = hallDetails; + } + + public ReasonMaster getReasonMaster() { + return reasonMaster; + } + + public void setReasonMaster(ReasonMaster reasonMaster) { + this.reasonMaster = reasonMaster; + } + + public LocalDate getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(LocalDate createdDate) { + this.createdDate = createdDate; + } +} diff --git a/src/main/java/com/gcc/communityHall/paymentService/scheduler/PaymentStatusScheduler.java b/src/main/java/com/gcc/communityHall/paymentService/scheduler/PaymentStatusScheduler.java index 6a2d13b1..eca9e99e 100644 --- a/src/main/java/com/gcc/communityHall/paymentService/scheduler/PaymentStatusScheduler.java +++ b/src/main/java/com/gcc/communityHall/paymentService/scheduler/PaymentStatusScheduler.java @@ -1,7 +1,7 @@ package com.gcc.communityHall.paymentService.scheduler; // Import necessary packages -//package com.gcc.communityHall.paymentService.Scheduler; +// package com.gcc.communityHall.paymentService.Scheduler; import com.fasterxml.jackson.databind.ObjectMapper; import com.gcc.communityHall.entity.BookingCalendar; @@ -71,7 +71,7 @@ public class PaymentStatusScheduler { // @Scheduled(cron = "0 0 0 * * ?", zone = "Asia/Kolkata") //executed at 12:00 AM // @Scheduled(fixedRate = 900000) - @Scheduled(fixedRate = 30000) + @Scheduled(fixedRate = 60000) public void fetchAndSavePaymentStatus() { // System.out.println("Fetching Payment Status...At 12:00 AM IST"); System.out.println("Fetching Payment Status...At 15 min Testing"); diff --git a/src/main/java/com/gcc/communityHall/repository/HallDetailsRepository.java b/src/main/java/com/gcc/communityHall/repository/HallDetailsRepository.java index 99874dff..f67cc20f 100644 --- a/src/main/java/com/gcc/communityHall/repository/HallDetailsRepository.java +++ b/src/main/java/com/gcc/communityHall/repository/HallDetailsRepository.java @@ -18,12 +18,15 @@ public interface HallDetailsRepository extends JpaRepository getHallAvailablity(); @Query(value = "SELECT * FROM hall_details where hall_id NOT IN (:groupByHallIdToRemov) ",nativeQuery = true) List removeHallById(Set groupByHallIdToRemov); - @Query("SELECT h FROM HallDetails h WHERE h.division = :division") + @Query("SELECT h FROM HallDetails h WHERE h.division = :division ") List findByDivision(@Param("division") String division); - @Query("SELECT h FROM HallDetails h WHERE h.zone = :zone") + @Query("SELECT h FROM HallDetails h WHERE h.zone = :zone ") List findByZone(@Param("zone") String zone); - @Query("SELECT h FROM HallDetails h WHERE h.id = :hallId") + @Query("SELECT h FROM HallDetails h WHERE h.id = :hallId ") HallDetails findHallDetailsById(@Param("hallId") int hallId); + + @Query("SELECT h FROM HallDetails h WHERE h.id = :hallId and h.isActive = true ") + HallDetails findHallActiveDetailsById(@Param("hallId") int hallId); @Query(value = "SELECT zone,division FROM hall_details ",nativeQuery = true ) List> getZoneAndDivision(); @@ -31,13 +34,13 @@ public interface HallDetailsRepository extends JpaRepository> getDivision(String zone); - @Query(value = "SELECT hall_id, hall_name FROM hall_details", nativeQuery = true) + @Query(value = "SELECT hall_id, hall_name FROM hall_details where is_active = 1 ", nativeQuery = true) List> getAllHalls(); - @Query(value = "SELECT hall_id, hall_name FROM hall_details WHERE zone = :zone", nativeQuery = true) + @Query(value = "SELECT hall_id, hall_name FROM hall_details WHERE zone = :zone and is_active = 1 ", nativeQuery = true) List> getHallsByZone(@Param("zone") String zone); - @Query(value = "SELECT hall_id AS hallId, hall_name AS hallName FROM hall_details WHERE zone IN (:zones)", nativeQuery = true) + @Query(value = "SELECT hall_id AS hallId, hall_name AS hallName FROM hall_details WHERE zone IN (:zones) and is_active = 1 ", nativeQuery = true) List> getHallsByZones(@Param("zones") List zones); @Query(value = "SELECT * FROM hall_details WHERE is_active = 1 order by hall_name asc", nativeQuery = true) @@ -69,7 +72,7 @@ public interface HallDetailsRepository extends JpaRepository> getHallDetailsByZone(@Param("zone") String zone); -@Query(value = "SELECT zone,division,hall_id,hall_name FROM hall_details ",nativeQuery = true ) +@Query(value = "SELECT zone,division,hall_id,hall_name FROM hall_details where is_active = 1 ",nativeQuery = true ) List> getZonesAndDivisions(); @@ -98,13 +101,19 @@ public interface HallDetailsRepository extends JpaRepository> getHallCountsForOfficer(@Param("zone") String zone); - @Query(value = "SELECT hall_name FROM hall_details WHERE hall_id = :hall_id", nativeQuery = true) + @Query(value = "SELECT hall_name FROM hall_details WHERE hall_id = :hall_id and is_active = 1 ", nativeQuery = true) String findHallNameById(@Param("hall_id") int hallId); - @Query("SELECT DISTINCT h.division FROM HallDetails h WHERE h.zone = :zone") + @Query("SELECT DISTINCT h.division FROM HallDetails h WHERE h.zone = :zone ") List findDistinctDivisionsByZone(@Param("zone") String zone); // Query to get hall names by division - @Query("SELECT h.hallName FROM HallDetails h WHERE h.division = :division") + @Query("SELECT h.hallName FROM HallDetails h WHERE h.division = :division and h.isActive = true ") List findHallsByDivision(@Param("division") String division); + + @Query("SELECT h FROM HallDetails h WHERE h.division = :division and h.isActive = true ") + List findActiveHallsByDivision(@Param("division") String division); + + @Query("SELECT h FROM HallDetails h WHERE h.zone = :zone and h.isActive = true ") + List findActiveHallsByZone(@Param("zone") String zone); } diff --git a/src/main/java/com/gcc/communityHall/repository/HallReasonRestrictionRepository.java b/src/main/java/com/gcc/communityHall/repository/HallReasonRestrictionRepository.java new file mode 100644 index 00000000..956da457 --- /dev/null +++ b/src/main/java/com/gcc/communityHall/repository/HallReasonRestrictionRepository.java @@ -0,0 +1,19 @@ +package com.gcc.communityHall.repository; + +import java.util.List; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +import com.gcc.communityHall.entity.HallReasonRestriction; + +@Repository +public interface HallReasonRestrictionRepository extends JpaRepository { + + List findByHallDetails_HallId(int hallId); + + @Query("SELECT r.reasonMaster.reasonId FROM HallReasonRestriction r WHERE r.hallDetails.hallId = :hallId") + List findReasonIdsByHallId(@Param("hallId") int hallId); +} diff --git a/src/main/java/com/gcc/communityHall/service/Impl/BookingServiceImpl.java b/src/main/java/com/gcc/communityHall/service/Impl/BookingServiceImpl.java index 4df8ff94..195e2551 100644 --- a/src/main/java/com/gcc/communityHall/service/Impl/BookingServiceImpl.java +++ b/src/main/java/com/gcc/communityHall/service/Impl/BookingServiceImpl.java @@ -67,6 +67,7 @@ import com.gcc.communityHall.repository.GccblockingDocumentsRepo; import com.gcc.communityHall.repository.HallDetailsConcessionRepo; import com.gcc.communityHall.repository.HallDetailsRepository; import com.gcc.communityHall.repository.ReasonMasterRepository; +import com.gcc.communityHall.repository.HallReasonRestrictionRepository; import com.gcc.communityHall.repository.SettlementHistoryRepository; import com.gcc.communityHall.repository.SettlementRepository; import com.gcc.communityHall.repository.UsersRepository; @@ -144,7 +145,7 @@ public class BookingServiceImpl implements BookingService { @Autowired private HttpSession session; @Autowired - private SettlementHistoryRepository settlementHistoryRepository; + private SettlementHistoryRepository settlementHistoryRepository; @Autowired private HallDetailsConcessionRepo hallDetailsConcessionRepo; @@ -152,6 +153,9 @@ public class BookingServiceImpl implements BookingService { @Autowired private ReasonMasterRepository reasonMasterRepository; + @Autowired + private HallReasonRestrictionRepository hallReasonRestrictionRepository; + @Autowired private ApplicationLogsRepository applicationLogsRepository; @@ -181,59 +185,56 @@ public class BookingServiceImpl implements BookingService { } return null; } - //ak + + // ak @Override -public BookingDetails getBookingByRefId(String refId) { - return bookingDetailsRepository.findByRefId(refId); -} -//ak -@Transactional -@Override -public void migrateOldBookingsToRefId() { + public BookingDetails getBookingByRefId(String refId) { + return bookingDetailsRepository.findByRefId(refId); + } + + // ak + @Transactional + @Override + public void migrateOldBookingsToRefId() { - List oldBookings = - bookingDetailsRepository.findAllOldBookingsWithoutRefId(); + List oldBookings = bookingDetailsRepository.findAllOldBookingsWithoutRefId(); - for (BookingDetails booking : oldBookings) { + for (BookingDetails booking : oldBookings) { - int bookingId = booking.getBookingId(); + int bookingId = booking.getBookingId(); - // Generate ref_id - String generatedRefId = UuidBookingUtil.generateRefIdForBooking(bookingId); + // Generate ref_id + String generatedRefId = UuidBookingUtil.generateRefIdForBooking(bookingId); - // Set into entity - booking.setBookingRefId(generatedRefId); + // Set into entity + booking.setBookingRefId(generatedRefId); - // Save - bookingDetailsRepository.save(booking); + // Save + bookingDetailsRepository.save(booking); - System.out.println("Migrated booking ID " + bookingId + - " → ref_id = " + generatedRefId); + System.out.println("Migrated booking ID " + bookingId + + " → ref_id = " + generatedRefId); + } } -} - - //ak + // ak @Transactional -public String getBookingRefIdByBookingId(int bookingId) { + public String getBookingRefIdByBookingId(int bookingId) { - String refId = bookingDetailsRepository.getRefIdByBookingId(bookingId); + String refId = bookingDetailsRepository.getRefIdByBookingId(bookingId); - // If missing → create new - if (refId == null || refId.trim().isEmpty()) { - - // Generate refId using coworkspace logic - refId = UuidBookingUtil.generateRefIdForBooking(bookingId); - - // Update using JPA repository - bookingDetailsRepository.updateRefId(refId, bookingId); - } - - return refId; -} + // If missing → create new + if (refId == null || refId.trim().isEmpty()) { + // Generate refId using coworkspace logic + refId = UuidBookingUtil.generateRefIdForBooking(bookingId); + // Update using JPA repository + bookingDetailsRepository.updateRefId(refId, bookingId); + } + return refId; + } @Override public BookingDetails updateBookingDetails(BookingDetails bd) { @@ -245,16 +246,18 @@ public String getBookingRefIdByBookingId(int bookingId) { Optional booking = bookingDetailsRepository.findById(bookingId); if (booking.isPresent()) { BookingDetails book = booking.get(); - /*BookingHistory bookingHistory = new BookingHistory(); - bookingHistory.setBookingDetails(book); - bookingHistory.setStartDate(book.getStartDate()); - bookingHistory.setEndDate(book.getEndDate()); - bookingHistory.setBookingStatus(book.getBookingStatus()); - bookingHistory.setComments(book.getComments()); - bookingHistory.setCdate(new Date()); - bookingHistory.setRefundStatus(book.getRefundStatus()); - System.out.println("bookingHistory.."+bookingHistory); - bookingHistoryRepository.save(bookingHistory);*/ + /* + * BookingHistory bookingHistory = new BookingHistory(); + * bookingHistory.setBookingDetails(book); + * bookingHistory.setStartDate(book.getStartDate()); + * bookingHistory.setEndDate(book.getEndDate()); + * bookingHistory.setBookingStatus(book.getBookingStatus()); + * bookingHistory.setComments(book.getComments()); + * bookingHistory.setCdate(new Date()); + * bookingHistory.setRefundStatus(book.getRefundStatus()); + * System.out.println("bookingHistory.."+bookingHistory); + * bookingHistoryRepository.save(bookingHistory); + */ book.setBookingStatus(status); book.setComments(comments); @@ -265,7 +268,8 @@ public String getBookingRefIdByBookingId(int bookingId) { } @Override - public String confirmTheDateAndSlot(String fromDate, String toDate, int days, int fromStartingSlot, int fromEndingSlot, int toStartingSlot, int toEndingSlot, int bookingId, int userId) { + public String confirmTheDateAndSlot(String fromDate, String toDate, int days, int fromStartingSlot, + int fromEndingSlot, int toStartingSlot, int toEndingSlot, int bookingId, int userId) { return null; } @@ -292,35 +296,45 @@ public String getBookingRefIdByBookingId(int bookingId) { for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) { BookingCalendar bookingCalendar = bookingCalendarRepository.findByBdateAndHallId(date, hallId); - if (bookingCalendar != null) { - // System.out.println(bookingCalendar.toString()); + // System.out.println(bookingCalendar.toString()); // System.out.println("date:-"+date ); - // System.out.println("bookingDetails.getEndingSlot() :- "+bookingDetails.getEndingSlot()); - //System.out.println("bookingCalendar.isMorningSlot():-"+bookingCalendar.isMorningSlot()); - //System.out.println(date.equals(endDate) && bookingDetails.getEndingSlot() == 1 && bookingCalendar.isMorningSlot()); - //System.out.println(); + // System.out.println("bookingDetails.getEndingSlot() :- + // "+bookingDetails.getEndingSlot()); + // System.out.println("bookingCalendar.isMorningSlot():-"+bookingCalendar.isMorningSlot()); + // System.out.println(date.equals(endDate) && bookingDetails.getEndingSlot() == + // 1 && bookingCalendar.isMorningSlot()); + // System.out.println(); // Check if the slot is already occupied if (bookingCalendar.getIs_blocked()) { throw new RuntimeException("GCC Blocked Date"); - } else if ((date.equals(startDate) && bookingDetails.getStartingSlot() == 1 && bookingCalendar.isMorningSlot()) || - (date.equals(startDate) && bookingDetails.getStartingSlot() == 2 && bookingCalendar.isEveningSlot()) || - (date.equals(endDate) && bookingDetails.getEndingSlot() == 1 && bookingCalendar.isMorningSlot()) || - (date.equals(endDate) && bookingDetails.getEndingSlot() == 2 && bookingCalendar.isEveningSlot())) { - - //System.out.println("booking slot occupied:- 218"); + } else if ((date.equals(startDate) && bookingDetails.getStartingSlot() == 1 + && bookingCalendar.isMorningSlot()) || + (date.equals(startDate) && bookingDetails.getStartingSlot() == 2 + && bookingCalendar.isEveningSlot()) + || + (date.equals(endDate) && bookingDetails.getEndingSlot() == 1 + && bookingCalendar.isMorningSlot()) + || + (date.equals(endDate) && bookingDetails.getEndingSlot() == 2 + && bookingCalendar.isEveningSlot())) { + + // System.out.println("booking slot occupied:- 218"); throw new RuntimeException(exMsg); } else if (bookingCalendar.isMorningSlot() && bookingCalendar.isEveningSlot()) { - //System.out.println("booking slot occupied:- 221"); + // System.out.println("booking slot occupied:- 221"); throw new RuntimeException(exMsg); } else if (!date.equals(endDate) && i != 0 && i != Math.round(bookingDetails.getNoOfDays() - 1) && (bookingCalendar.isMorningSlot() || bookingCalendar.isEveningSlot())) { - //System.out.println("booking slot occupied:- 227 :-"+Math.round(bookingDetails.getNoOfDays()-1) ); + // System.out.println("booking slot occupied:- 227 + // :-"+Math.round(bookingDetails.getNoOfDays()-1) ); throw new RuntimeException(exMsg); - } else if (date.equals(endDate) && bookingDetails.getEndingSlot() == 2 && bookingCalendar.isMorningSlot() + } else if (date.equals(endDate) && bookingDetails.getEndingSlot() == 2 + && bookingCalendar.isMorningSlot() && i != 0 && i == Math.round(bookingDetails.getNoOfDays() - 1)) { - // System.out.println("booking slot occupied:- 240 :-"+Math.round(bookingDetails.getNoOfDays()-1) ); + // System.out.println("booking slot occupied:- 240 + // :-"+Math.round(bookingDetails.getNoOfDays()-1) ); throw new RuntimeException(exMsg); } @@ -338,7 +352,7 @@ public String getBookingRefIdByBookingId(int bookingId) { // Mark the appropriate slot as booked based on starting and ending slots if (date.equals(startDate)) { - //System.out.println(i + "start :-"+bookingCalendar.toString()); + // System.out.println(i + "start :-"+bookingCalendar.toString()); if (bookingDetails.getStartingSlot() == 1) { bookingCalendar.setMorningSlot(true); @@ -348,7 +362,8 @@ public String getBookingRefIdByBookingId(int bookingId) { bookingCalendar.setEveningSlot(true); bookingCalendar.setBookingId_2(String.valueOf(bookingId)); bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1); - } else if (startDate.equals(endDate) && bookingDetails.getStartingSlot() == 1 && bookingDetails.getEndingSlot() == 2) { + } else if (startDate.equals(endDate) && bookingDetails.getStartingSlot() == 1 + && bookingDetails.getEndingSlot() == 2) { bookingCalendar.setEveningSlot(true); bookingCalendar.setBookingId_2(String.valueOf(bookingId)); bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1); @@ -391,34 +406,62 @@ public String getBookingRefIdByBookingId(int bookingId) { return statusMessage; - /*String reason = bookingDetails.getReason(); - ReasonMaster reasondetails = reasonMasterRepository.findByReason(reason); - String reasoncode = reasondetails.getReasoncode(); - if (reasoncode == null) { - reasoncode = ""; // or any default value - } - if (reasoncode.equals("CGE") || reasoncode.equals("CAO") || reasoncode.equals("SGE")) { - updateBookingStatusById(bookingDetails.getBookingId(), BookingDetails.BookingStatus.WAITING_FOR_NOC, "Waiting For NOC Documents"); - String bookingconfirmationmsg = "Your booking ID " + bookingDetails.getBookingId() + " on " + bookingDetails.getBookingDate() + " has been confirmed successfully. Thanks for using GCC Community Hall Booking System."; - String urlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + bookingDetails.getUsers().getMobileNo() + "&from=GCCCRP&body=" + bookingconfirmationmsg + "&entityid=1401572690000011081&templateid=1407172346459428987"; - String whatsupmsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + bookingDetails.getUsers().getMobileNo() + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+booking+with+ID+" + bookingDetails.getBookingId() + "+on+" + bookingDetails.getBookingDate() + "+has+been+successfully+confirmed.+%0AThanks+for+using+GCC+Community+Hall+Booking+System."; - whatsappMsgServiceImpl.sendMsg(whatsupmsg); - whatsappMsgServiceImpl.sendSMS(urlString); - return "Waiting For NOC Documents"; - } else { - updateBookingStatusById(bookingDetails.getBookingId(), BookingDetails.BookingStatus.APPROVED, "Booking Confirmed Successfully"); - String bookingconfirmationmsg = "Your booking ID " + bookingDetails.getBookingId() + " on " + bookingDetails.getStartDate() + " has been confirmed successfully. Thanks for using GCC Community Hall Booking System."; - String urlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + bookingDetails.getUsers().getMobileNo() + "&from=GCCCRP&body=" + bookingconfirmationmsg + "&entityid=1401572690000011081&templateid=1407172346459428987"; - String whatsupmsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + bookingDetails.getUsers().getMobileNo() + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+booking+with+ID+" + bookingDetails.getBookingId() + "+on+" + bookingDetails.getStartDate() + "+has+been+successfully+confirmed.+%0AThanks+for+using+GCC+Community+Hall+Booking+System."; - whatsappMsgServiceImpl.sendMsg(whatsupmsg); - whatsappMsgServiceImpl.sendSMS(urlString); - return "Booking confirmed successfully"; - }*/ + /* + * String reason = bookingDetails.getReason(); + * ReasonMaster reasondetails = reasonMasterRepository.findByReason(reason); + * String reasoncode = reasondetails.getReasoncode(); + * if (reasoncode == null) { + * reasoncode = ""; // or any default value + * } + * if (reasoncode.equals("CGE") || reasoncode.equals("CAO") || + * reasoncode.equals("SGE")) { + * updateBookingStatusById(bookingDetails.getBookingId(), + * BookingDetails.BookingStatus.WAITING_FOR_NOC, "Waiting For NOC Documents"); + * String bookingconfirmationmsg = "Your booking ID " + + * bookingDetails.getBookingId() + " on " + bookingDetails.getBookingDate() + + * " has been confirmed successfully. Thanks for using GCC Community Hall Booking System." + * ; + * String urlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + + * bookingDetails.getUsers().getMobileNo() + "&from=GCCCRP&body=" + + * bookingconfirmationmsg + + * "&entityid=1401572690000011081&templateid=1407172346459428987"; + * String whatsupmsg = + * "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + * + bookingDetails.getUsers().getMobileNo() + + * "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+booking+with+ID+" + * + bookingDetails.getBookingId() + "+on+" + bookingDetails.getBookingDate() + + * "+has+been+successfully+confirmed.+%0AThanks+for+using+GCC+Community+Hall+Booking+System."; + * whatsappMsgServiceImpl.sendMsg(whatsupmsg); + * whatsappMsgServiceImpl.sendSMS(urlString); + * return "Waiting For NOC Documents"; + * } else { + * updateBookingStatusById(bookingDetails.getBookingId(), + * BookingDetails.BookingStatus.APPROVED, "Booking Confirmed Successfully"); + * String bookingconfirmationmsg = "Your booking ID " + + * bookingDetails.getBookingId() + " on " + bookingDetails.getStartDate() + + * " has been confirmed successfully. Thanks for using GCC Community Hall Booking System." + * ; + * String urlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + + * bookingDetails.getUsers().getMobileNo() + "&from=GCCCRP&body=" + + * bookingconfirmationmsg + + * "&entityid=1401572690000011081&templateid=1407172346459428987"; + * String whatsupmsg = + * "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + * + bookingDetails.getUsers().getMobileNo() + + * "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+booking+with+ID+" + * + bookingDetails.getBookingId() + "+on+" + bookingDetails.getStartDate() + + * "+has+been+successfully+confirmed.+%0AThanks+for+using+GCC+Community+Hall+Booking+System."; + * whatsappMsgServiceImpl.sendMsg(whatsupmsg); + * whatsappMsgServiceImpl.sendSMS(urlString); + * return "Booking confirmed successfully"; + * } + */ } catch (Exception e) { e.printStackTrace(); bookingFailure(bookingDetails, 2); // System.out.println(bookingDetails.getBookingStatus()+","+bookingDetails.getRefundStatus()+","+bookingDetails.getComments()); - //return "redirect:/communityhall/user/acknowledgement?bookingId=" + bookingDetails.getBookingId(); + // return "redirect:/communityhall/user/acknowledgement?bookingId=" + + // bookingDetails.getBookingId(); return "redirect:/communityhall/user/acknowledgement?ref_id=" + bookingDetails.getBookingRefId(); } @@ -429,19 +472,27 @@ public String getBookingRefIdByBookingId(int bookingId) { try { String reason = bookingDetails.getReason(); ReasonMaster reasonDetails = reasonMasterRepository.findByReason(reason); - String reasonCode = (reasonDetails != null && reasonDetails.getReasoncode() != null) ? reasonDetails.getReasoncode() : ""; + String reasonCode = (reasonDetails != null && reasonDetails.getReasoncode() != null) + ? reasonDetails.getReasoncode() + : ""; String bookingconfirmationmsg, urlString, whatsupmsg; if (reasonCode.equals("CGE") || reasonCode.equals("CAO") || reasonCode.equals("SGE")) { - updateBookingStatusById(bookingDetails.getBookingId(), BookingDetails.BookingStatus.WAITING_FOR_NOC, "Waiting For NOC Documents"); + updateBookingStatusById(bookingDetails.getBookingId(), BookingDetails.BookingStatus.WAITING_FOR_NOC, + "Waiting For NOC Documents"); - bookingconfirmationmsg = "Your booking ID " + bookingDetails.getBookingId() + " on " + bookingDetails.getBookingDate() + " has been confirmed successfully. Thanks for using GCC Community Hall Booking System."; + bookingconfirmationmsg = "Your booking ID " + bookingDetails.getBookingId() + " on " + + bookingDetails.getBookingDate() + + " has been confirmed successfully. Thanks for using GCC Community Hall Booking System."; - urlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + bookingDetails.getUsers().getMobileNo() + - "&from=GCCCRP&body=" + bookingconfirmationmsg + "&entityid=1401572690000011081&templateid=1407172346459428987"; + urlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + + bookingDetails.getUsers().getMobileNo() + + "&from=GCCCRP&body=" + bookingconfirmationmsg + + "&entityid=1401572690000011081&templateid=1407172346459428987"; - whatsupmsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + + whatsupmsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + + bookingDetails.getUsers().getMobileNo() + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+booking+with+ID+" + bookingDetails.getBookingId() + "+on+" + bookingDetails.getBookingDate() + @@ -452,14 +503,20 @@ public String getBookingRefIdByBookingId(int bookingId) { return "Waiting For NOC Documents"; } else { - updateBookingStatusById(bookingDetails.getBookingId(), BookingDetails.BookingStatus.APPROVED, "Booking Confirmed Successfully"); + updateBookingStatusById(bookingDetails.getBookingId(), BookingDetails.BookingStatus.APPROVED, + "Booking Confirmed Successfully"); - bookingconfirmationmsg = "Your booking ID " + bookingDetails.getBookingId() + " on " + bookingDetails.getStartDate() + " has been confirmed successfully. Thanks for using GCC Community Hall Booking System."; + bookingconfirmationmsg = "Your booking ID " + bookingDetails.getBookingId() + " on " + + bookingDetails.getStartDate() + + " has been confirmed successfully. Thanks for using GCC Community Hall Booking System."; - urlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + bookingDetails.getUsers().getMobileNo() + - "&from=GCCCRP&body=" + bookingconfirmationmsg + "&entityid=1401572690000011081&templateid=1407172346459428987"; + urlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + + bookingDetails.getUsers().getMobileNo() + + "&from=GCCCRP&body=" + bookingconfirmationmsg + + "&entityid=1401572690000011081&templateid=1407172346459428987"; - whatsupmsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + + whatsupmsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + + bookingDetails.getUsers().getMobileNo() + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+booking+with+ID+" + bookingDetails.getBookingId() + "+on+" + bookingDetails.getStartDate() + @@ -475,7 +532,6 @@ public String getBookingRefIdByBookingId(int bookingId) { } } - @Override @Transactional public String confirmStateBooking(int bookingId) { @@ -500,30 +556,41 @@ public String getBookingRefIdByBookingId(int bookingId) { BookingCalendar bookingCalendar = bookingCalendarRepository.findByBdateAndHallId(date, hallId); if (bookingCalendar != null) { - // System.out.println(bookingCalendar.toString()); + // System.out.println(bookingCalendar.toString()); // System.out.println("date:-"+date ); - // System.out.println("bookingDetails.getEndingSlot() :- "+bookingDetails.getEndingSlot()); - //System.out.println("bookingCalendar.isMorningSlot():-"+bookingCalendar.isMorningSlot()); - //System.out.println(date.equals(endDate) && bookingDetails.getEndingSlot() == 1 && bookingCalendar.isMorningSlot()); - //System.out.println(); + // System.out.println("bookingDetails.getEndingSlot() :- + // "+bookingDetails.getEndingSlot()); + // System.out.println("bookingCalendar.isMorningSlot():-"+bookingCalendar.isMorningSlot()); + // System.out.println(date.equals(endDate) && bookingDetails.getEndingSlot() == + // 1 && bookingCalendar.isMorningSlot()); + // System.out.println(); // Check if the slot is already occupied - if ((date.equals(startDate) && bookingDetails.getStartingSlot() == 1 && bookingCalendar.isMorningSlot()) || - (date.equals(startDate) && bookingDetails.getStartingSlot() == 2 && bookingCalendar.isEveningSlot()) || - (date.equals(endDate) && bookingDetails.getEndingSlot() == 1 && bookingCalendar.isMorningSlot()) || - (date.equals(endDate) && bookingDetails.getEndingSlot() == 2 && bookingCalendar.isEveningSlot())) { - //System.out.println("booking slot occupied:- 218"); + if ((date.equals(startDate) && bookingDetails.getStartingSlot() == 1 + && bookingCalendar.isMorningSlot()) || + (date.equals(startDate) && bookingDetails.getStartingSlot() == 2 + && bookingCalendar.isEveningSlot()) + || + (date.equals(endDate) && bookingDetails.getEndingSlot() == 1 + && bookingCalendar.isMorningSlot()) + || + (date.equals(endDate) && bookingDetails.getEndingSlot() == 2 + && bookingCalendar.isEveningSlot())) { + // System.out.println("booking slot occupied:- 218"); throw new RuntimeException(exMsg); } else if (bookingCalendar.isMorningSlot() && bookingCalendar.isEveningSlot()) { - //System.out.println("booking slot occupied:- 221"); + // System.out.println("booking slot occupied:- 221"); throw new RuntimeException(exMsg); } else if (!date.equals(endDate) && i != 0 && i != Math.round(bookingDetails.getNoOfDays() - 1) && (bookingCalendar.isMorningSlot() || bookingCalendar.isEveningSlot())) { - //System.out.println("booking slot occupied:- 227 :-"+Math.round(bookingDetails.getNoOfDays()-1) ); + // System.out.println("booking slot occupied:- 227 + // :-"+Math.round(bookingDetails.getNoOfDays()-1) ); throw new RuntimeException(exMsg); - } else if (date.equals(endDate) && bookingDetails.getEndingSlot() == 2 && bookingCalendar.isMorningSlot() + } else if (date.equals(endDate) && bookingDetails.getEndingSlot() == 2 + && bookingCalendar.isMorningSlot() && i != 0 && i == Math.round(bookingDetails.getNoOfDays() - 1)) { - // System.out.println("booking slot occupied:- 240 :-"+Math.round(bookingDetails.getNoOfDays()-1) ); + // System.out.println("booking slot occupied:- 240 + // :-"+Math.round(bookingDetails.getNoOfDays()-1) ); throw new RuntimeException(exMsg); } @@ -537,7 +604,7 @@ public String getBookingRefIdByBookingId(int bookingId) { // Mark the appropriate slot as booked based on starting and ending slots if (date.equals(startDate)) { - //System.out.println(i + "start :-"+bookingCalendar.toString()); + // System.out.println(i + "start :-"+bookingCalendar.toString()); if (bookingDetails.getStartingSlot() == 1) { bookingCalendar.setMorningSlot(true); @@ -547,7 +614,8 @@ public String getBookingRefIdByBookingId(int bookingId) { bookingCalendar.setEveningSlot(true); bookingCalendar.setBookingId_2(String.valueOf(bookingId)); bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1); - } else if (startDate.equals(endDate) && bookingDetails.getStartingSlot() == 1 && bookingDetails.getEndingSlot() == 2) { + } else if (startDate.equals(endDate) && bookingDetails.getStartingSlot() == 1 + && bookingDetails.getEndingSlot() == 2) { bookingCalendar.setEveningSlot(true); bookingCalendar.setBookingId_2(String.valueOf(bookingId)); bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1); @@ -586,61 +654,93 @@ public String getBookingRefIdByBookingId(int bookingId) { bookingCalendarRepository.save(bookingCalendar); i++; } - updateBookingStatusById(bookingDetails.getBookingId(), BookingDetails.BookingStatus.WAITING_FOR_NOC, "Waiting for NOC Documents"); - String bookingconfirmationmsg = "Your booking ID " + bookingDetails.getBookingId() + " on " + bookingDetails.getBookingDate() + " has been confirmed successfully. Thanks for using GCC Community Hall Booking System."; - String urlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + bookingDetails.getUsers().getMobileNo() + "&from=GCCCRP&body=" + bookingconfirmationmsg + "&entityid=1401572690000011081&templateid=1407172346459428987"; - String whatsupmsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + bookingDetails.getUsers().getMobileNo() + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+booking+with+ID+" + bookingDetails.getBookingId() + "+on+" + bookingDetails.getBookingDate() + "+has+been+successfully+confirmed.+%0AThanks+for+using+GCC+Community+Hall+Booking+System."; + updateBookingStatusById(bookingDetails.getBookingId(), BookingDetails.BookingStatus.WAITING_FOR_NOC, + "Waiting for NOC Documents"); + String bookingconfirmationmsg = "Your booking ID " + bookingDetails.getBookingId() + " on " + + bookingDetails.getBookingDate() + + " has been confirmed successfully. Thanks for using GCC Community Hall Booking System."; + String urlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + + bookingDetails.getUsers().getMobileNo() + "&from=GCCCRP&body=" + bookingconfirmationmsg + + "&entityid=1401572690000011081&templateid=1407172346459428987"; + String whatsupmsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + + bookingDetails.getUsers().getMobileNo() + + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+booking+with+ID+" + + bookingDetails.getBookingId() + "+on+" + bookingDetails.getBookingDate() + + "+has+been+successfully+confirmed.+%0AThanks+for+using+GCC+Community+Hall+Booking+System."; whatsappMsgServiceImpl.sendMsg(whatsupmsg); whatsappMsgServiceImpl.sendSMS(urlString); - // return "redirect:/communityhall/user/acknowledgement?bookingId=" + bookingDetails.getBookingId(); - return "redirect:/communityhall/user/acknowledgement?ref_id=" + bookingDetails.getBookingRefId(); + // return "redirect:/communityhall/user/acknowledgement?bookingId=" + + // bookingDetails.getBookingId(); + return "redirect:/communityhall/user/acknowledgement?ref_id=" + bookingDetails.getBookingRefId(); } catch (Exception e) { bookingFailure(bookingDetails, 2); // System.out.println(bookingDetails.getBookingStatus()+","+bookingDetails.getRefundStatus()+","+bookingDetails.getComments()); - // return "redirect:/communityhall/user/acknowledgement?bookingId=" + bookingDetails.getBookingId(); - return "redirect:/communityhall/user/acknowledgement?ref_id=" + bookingDetails.getBookingRefId(); + // return "redirect:/communityhall/user/acknowledgement?bookingId=" + + // bookingDetails.getBookingId(); + return "redirect:/communityhall/user/acknowledgement?ref_id=" + bookingDetails.getBookingRefId(); } } - /*@Transactional(propagation = Propagation.REQUIRES_NEW) - public String bookingFailure(BookingDetails bookingDetails) { - // System.out.println("Booking Failure:-"+bookingDetails.getBookingId()); - bookingDetails.setBookingStatus(BookingStatus.REFUNDED); - bookingDetails.setComments("Slot occupied by other user,Amount paid will be refunded."); - bookingDetailsRepository.save(bookingDetails); - if (!(bookingDetails.getRefundStatus() == RefundStatus.COMPLETED) && !(bookingDetails.getRefundStatus() == RefundStatus.CLOSED)) { - // BookingDetails bd =updateBookingStatusById(bookingDetails.getBookingId(), BookingDetails.BookingStatus.REFUNDED, "slot occupied Refund will happen shortly"); - applicationLogService.saveLog(bookingDetails.getBookingId(), ApplicationLogs.logsOfMsg.REFUNDED.toString(), "Refund will happen shortly"); - try { - String refundedMsg = paymentGatewayService.refundTheAmount(bookingDetails.getBookingId(), bookingDetails.getUsers().getUserId()); - //System.out.println("refundedMsg=="+refundedMsg); - if (refundedMsg.equals("Refunded")) { - //System.out.println("Refund completed........"); - bookingDetails.setRefundStatus(BookingDetails.RefundStatus.COMPLETED); - bookingDetailsRepository.save(bookingDetails); - //System.out.println("refundStatus===="+bookingDetails.getRefundStatus()); - long mobile = bookingDetails.getUsers().getMobileNo(); - int bookingId = bookingDetails.getBookingId(); - double refundAmt = bookingDetails.getAmountReceived(); -// Thread thread = new Thread(() -> { - String settlementrefundsms = "Your refund amount of Rs. " + refundAmt + " for Booking ID " + bookingId + " has been initiated. The amount will be credited to your account within 3 to 15 days. Thanks for using the GCC Community Hall Booking System."; - String settlementrefundurlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + mobile + "&from=GCCCRP&body=" + settlementrefundsms + "&entityid=1401572690000011081&templateid=1407172346804951524"; - String settlementrefundwhatsupmsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + mobile + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+refund+of+Rs.+" + refundAmt + "+for+Booking+ID+" + bookingId + "+has+been+initiated.+%0AThe+amount+will+be+credited+to+your+account+within+3+to+15+days."; - whatsappMsgServiceImpl.sendMsg(settlementrefundwhatsupmsg); - whatsappMsgServiceImpl.sendSMS(settlementrefundurlString); -// }); -// thread.start(); - return "Success"; - } - } catch (Exception e) { - applicationLogService.saveLog(bookingDetails.getBookingId(), ApplicationLogs.logsOfMsg.ERROR.toString(), "Refund Error"); - return "error"; - } - } - return "error"; - }*/ + /* + * @Transactional(propagation = Propagation.REQUIRES_NEW) + * public String bookingFailure(BookingDetails bookingDetails) { + * // System.out.println("Booking Failure:-"+bookingDetails.getBookingId()); + * bookingDetails.setBookingStatus(BookingStatus.REFUNDED); + * bookingDetails. + * setComments("Slot occupied by other user,Amount paid will be refunded."); + * bookingDetailsRepository.save(bookingDetails); + * if (!(bookingDetails.getRefundStatus() == RefundStatus.COMPLETED) && + * !(bookingDetails.getRefundStatus() == RefundStatus.CLOSED)) { + * // BookingDetails bd =updateBookingStatusById(bookingDetails.getBookingId(), + * BookingDetails.BookingStatus.REFUNDED, + * "slot occupied Refund will happen shortly"); + * applicationLogService.saveLog(bookingDetails.getBookingId(), + * ApplicationLogs.logsOfMsg.REFUNDED.toString(), "Refund will happen shortly"); + * try { + * String refundedMsg = + * paymentGatewayService.refundTheAmount(bookingDetails.getBookingId(), + * bookingDetails.getUsers().getUserId()); + * //System.out.println("refundedMsg=="+refundedMsg); + * if (refundedMsg.equals("Refunded")) { + * //System.out.println("Refund completed........"); + * bookingDetails.setRefundStatus(BookingDetails.RefundStatus.COMPLETED); + * bookingDetailsRepository.save(bookingDetails); + * //System.out.println("refundStatus===="+bookingDetails.getRefundStatus()); + * long mobile = bookingDetails.getUsers().getMobileNo(); + * int bookingId = bookingDetails.getBookingId(); + * double refundAmt = bookingDetails.getAmountReceived(); + * // Thread thread = new Thread(() -> { + * String settlementrefundsms = "Your refund amount of Rs. " + refundAmt + + * " for Booking ID " + bookingId + + * " has been initiated. The amount will be credited to your account within 3 to 15 days. Thanks for using the GCC Community Hall Booking System." + * ; + * String settlementrefundurlString = + * "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + mobile + + * "&from=GCCCRP&body=" + settlementrefundsms + + * "&entityid=1401572690000011081&templateid=1407172346804951524"; + * String settlementrefundwhatsupmsg = + * "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + * + mobile + + * "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+refund+of+Rs.+" + * + refundAmt + "+for+Booking+ID+" + bookingId + + * "+has+been+initiated.+%0AThe+amount+will+be+credited+to+your+account+within+3+to+15+days."; + * whatsappMsgServiceImpl.sendMsg(settlementrefundwhatsupmsg); + * whatsappMsgServiceImpl.sendSMS(settlementrefundurlString); + * // }); + * // thread.start(); + * return "Success"; + * } + * } catch (Exception e) { + * applicationLogService.saveLog(bookingDetails.getBookingId(), + * ApplicationLogs.logsOfMsg.ERROR.toString(), "Refund Error"); + * return "error"; + * } + * } + * return "error"; + * } + */ @Transactional(propagation = Propagation.REQUIRES_NEW) public String bookingFailure(BookingDetails bookingDetails, int flag) { @@ -652,32 +752,45 @@ public String getBookingRefIdByBookingId(int bookingId) { bookingDetails.setComments("Slot occupied by other user,Amount paid will be refunded."); } bookingDetailsRepository.save(bookingDetails); - if (!(bookingDetails.getRefundStatus() == RefundStatus.COMPLETED) && !(bookingDetails.getRefundStatus() == RefundStatus.CLOSED)) { - // BookingDetails bd =updateBookingStatusById(bookingDetails.getBookingId(), BookingDetails.BookingStatus.REFUNDED, "slot occupied Refund will happen shortly"); - applicationLogService.saveLog(bookingDetails.getBookingId(), ApplicationLogs.logsOfMsg.REFUNDED.toString(), "Refund will happen shortly"); + if (!(bookingDetails.getRefundStatus() == RefundStatus.COMPLETED) + && !(bookingDetails.getRefundStatus() == RefundStatus.CLOSED)) { + // BookingDetails bd =updateBookingStatusById(bookingDetails.getBookingId(), + // BookingDetails.BookingStatus.REFUNDED, "slot occupied Refund will happen + // shortly"); + applicationLogService.saveLog(bookingDetails.getBookingId(), ApplicationLogs.logsOfMsg.REFUNDED.toString(), + "Refund will happen shortly"); try { - String refundedMsg = paymentGatewayService.refundTheAmount(bookingDetails.getBookingId(), bookingDetails.getUsers().getUserId()); - //System.out.println("refundedMsg=="+refundedMsg); + String refundedMsg = paymentGatewayService.refundTheAmount(bookingDetails.getBookingId(), + bookingDetails.getUsers().getUserId()); + // System.out.println("refundedMsg=="+refundedMsg); if (refundedMsg.equals("Refunded")) { - //System.out.println("Refund completed........"); + // System.out.println("Refund completed........"); bookingDetails.setRefundStatus(BookingDetails.RefundStatus.COMPLETED); bookingDetailsRepository.save(bookingDetails); - //System.out.println("refundStatus===="+bookingDetails.getRefundStatus()); + // System.out.println("refundStatus===="+bookingDetails.getRefundStatus()); long mobile = bookingDetails.getUsers().getMobileNo(); int bookingId = bookingDetails.getBookingId(); double refundAmt = bookingDetails.getAmountReceived(); -// Thread thread = new Thread(() -> { - String settlementrefundsms = "Your refund amount of Rs. " + refundAmt + " for Booking ID " + bookingId + " has been initiated. The amount will be credited to your account within 3 to 15 days. Thanks for using the GCC Community Hall Booking System."; - String settlementrefundurlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + mobile + "&from=GCCCRP&body=" + settlementrefundsms + "&entityid=1401572690000011081&templateid=1407172346804951524"; - String settlementrefundwhatsupmsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + mobile + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+refund+of+Rs.+" + refundAmt + "+for+Booking+ID+" + bookingId + "+has+been+initiated.+%0AThe+amount+will+be+credited+to+your+account+within+3+to+15+days."; + // Thread thread = new Thread(() -> { + String settlementrefundsms = "Your refund amount of Rs. " + refundAmt + " for Booking ID " + + bookingId + + " has been initiated. The amount will be credited to your account within 3 to 15 days. Thanks for using the GCC Community Hall Booking System."; + String settlementrefundurlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + mobile + + "&from=GCCCRP&body=" + settlementrefundsms + + "&entityid=1401572690000011081&templateid=1407172346804951524"; + String settlementrefundwhatsupmsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + + mobile + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+refund+of+Rs.+" + + refundAmt + "+for+Booking+ID+" + bookingId + + "+has+been+initiated.+%0AThe+amount+will+be+credited+to+your+account+within+3+to+15+days."; whatsappMsgServiceImpl.sendMsg(settlementrefundwhatsupmsg); whatsappMsgServiceImpl.sendSMS(settlementrefundurlString); -// }); -// thread.start(); + // }); + // thread.start(); return "Success"; } } catch (Exception e) { - applicationLogService.saveLog(bookingDetails.getBookingId(), ApplicationLogs.logsOfMsg.ERROR.toString(), "Refund Error"); + applicationLogService.saveLog(bookingDetails.getBookingId(), ApplicationLogs.logsOfMsg.ERROR.toString(), + "Refund Error"); return "error"; } } @@ -693,11 +806,22 @@ public String getBookingRefIdByBookingId(int bookingId) { Integer userId = userSession.getUserId(); String counterId = userSession.getCounter(); - System.out.println("counterId.."+counterId); + System.out.println("counterId.." + counterId); - ReasonMaster reasonMaster = reasonMasterService.getReasonById(Integer.parseInt(formData.get("reasonId").toString())); + ReasonMaster reasonMaster = reasonMasterService + .getReasonById(Integer.parseInt(formData.get("reasonId").toString())); HallDetails hallDetails = hallDetailService.getHallById(Integer.parseInt(formData.get("hallId").toString())); Users user = userService.getUserById(userId); + + // Validate reason restriction for this hall + if (hallDetails != null && hallDetails.isReasonRestricted()) { + List allowedReasonIds = hallReasonRestrictionRepository + .findReasonIdsByHallId(hallDetails.getHallId()); + if (!allowedReasonIds.isEmpty() && !allowedReasonIds.contains(reasonMaster.getReasonId())) { + return Collections.singletonMap("status", "reason_restricted"); + } + } + String bookingId = formData.get("bookingId").toString(); if (bookingId != null && bookingId.equals("0")) { @@ -750,18 +874,20 @@ public String getBookingRefIdByBookingId(int bookingId) { String startingSlot_txt = formData.get("startingSlot").toString(); String endingSlot_txt = formData.get("endingSlot").toString(); - //double depositeamount = hallDetails.getDepositAmount() * daysrange; - double depositeamount = hallDetails.getDepositAmount() ; - System.out.println("depositeamount...."+depositeamount); + // double depositeamount = hallDetails.getDepositAmount() * daysrange; + double depositeamount = hallDetails.getDepositAmount(); + System.out.println("depositeamount...." + depositeamount); double halfDepositAmount = hallDetails.getHalfDepositAmount(); - System.out.println("halfDepositAmount...."+halfDepositAmount); - System.err.println("days.."+days); - System.err.println("daysrange.."+daysrange); - double Totaldepositeamount = calculateDepositAmount(daysrange, startingSlot_txt, endingSlot_txt, depositeamount, halfDepositAmount); - System.out.println("Totaldepositeamount.."+Totaldepositeamount); + System.out.println("halfDepositAmount...." + halfDepositAmount); + System.err.println("days.." + days); + System.err.println("daysrange.." + daysrange); + double Totaldepositeamount = calculateDepositAmount(daysrange, startingSlot_txt, endingSlot_txt, + depositeamount, halfDepositAmount); + System.out.println("Totaldepositeamount.." + Totaldepositeamount); depositeamount = Totaldepositeamount; // Calculate discount based on user type - if (usertype.equals("COUNCILLOR") || usertype.equals("PENSIONER") || usertype.equals("GCC_EMPLOYEE") || usertype.equals("PUBLIC")) { + if (usertype.equals("COUNCILLOR") || usertype.equals("PENSIONER") || usertype.equals("GCC_EMPLOYEE") + || usertype.equals("PUBLIC")) { discountAmount = (hallAmount * discount) / 100; hallAmount = hallAmount - discountAmount; double gstAmount = Math.round(hallAmount * hallDetails.getGst()) / 100.0; @@ -789,12 +915,13 @@ public String getBookingRefIdByBookingId(int bookingId) { reasoncode = ""; // or any default value } hs.put("reasoncode", reasoncode); - HallDetailsConcession governmentevents = hallDetailsConcessionRepo.findbyhallId(hallDetails.getHallId()); + HallDetailsConcession governmentevents = hallDetailsConcessionRepo + .findbyhallId(hallDetails.getHallId()); if (reasoncode.equals("SGE")) { if (startingSlot == 1 && endingSlot == 2) { discountAmount = (governmentevents.getFulldayhallamount() * hallDetails.getSGEdiscount()) / 100; hallAmount = governmentevents.getFulldayhallamount(); - hs.put("discount", hallDetails.getSGEdiscount()); // No discount for State Govt Event + hs.put("discount", hallDetails.getSGEdiscount()); // No discount for State Govt Event double cleaningCharges = governmentevents.getFullDayCleaningcharges(); double PASystem = governmentevents.getFulldayPAsystem(); double EB = governmentevents.getFulldayEBcharges(); @@ -813,7 +940,7 @@ public String getBookingRefIdByBookingId(int bookingId) { } else { hallAmount = governmentevents.getHalfdayhallamount(); discountAmount = (hallAmount * hallDetails.getSGEdiscount()) / 100; - hs.put("discount", hallDetails.getSGEdiscount()); // No discount for State Govt Event + hs.put("discount", hallDetails.getSGEdiscount()); // No discount for State Govt Event double cleaningCharges = governmentevents.getHalfDayCleaningcharges(); double PASystem = governmentevents.getHalfdayPAsystem(); double EB = governmentevents.getHalfdayEBcharges(); @@ -830,31 +957,37 @@ public String getBookingRefIdByBookingId(int bookingId) { hs.put("additionalcharges", additionalcharges); hs.put("totalAmount", truncatedTotalAmount); } - } /*else if (reasoncode.equals("CGE")) { - double hallAmountforcentral = calcHallAmount(hallDetails, daysrange, startingSlot, endingSlot); - double discountAmounts = (hallAmountforcentral * hallDetails.getCGEdiscount()) / 100; - hs.put("discount", hallDetails.getCGEdiscount()); // 50% discount for Central Govt Event - hallAmountforcentral = hallAmountforcentral - discountAmounts; - // Calculate GST and total amount - double gstAmount = Math.round(hallAmountforcentral * hallDetails.getGst()) / 100.0; - double totalAmount = hallAmountforcentral + gstAmount + depositeamount; - - // Truncate the total amount to two decimal places - //double truncatedTotalAmount = Math.floor(totalAmount * 100) / 100; - // Round the total amount to two decimal places - double truncatedTotalAmount = Math.round(totalAmount * 100.0) / 100.0; - - // Set the calculated amounts to bookingDetails - bookingDetails.setDepositAmount(depositeamount); - bookingDetails.setHallAmount(hallAmountforcentral); - bookingDetails.setGst(gstAmount); - bookingDetails.setAmountReceived(truncatedTotalAmount); - hs.put("totalAmount", truncatedTotalAmount); - }*/ else if (reasoncode.equals("CGE")) { + } /* + * else if (reasoncode.equals("CGE")) { + * double hallAmountforcentral = calcHallAmount(hallDetails, daysrange, + * startingSlot, endingSlot); + * double discountAmounts = (hallAmountforcentral * + * hallDetails.getCGEdiscount()) / 100; + * hs.put("discount", hallDetails.getCGEdiscount()); // 50% discount for Central + * Govt Event + * hallAmountforcentral = hallAmountforcentral - discountAmounts; + * // Calculate GST and total amount + * double gstAmount = Math.round(hallAmountforcentral * hallDetails.getGst()) / + * 100.0; + * double totalAmount = hallAmountforcentral + gstAmount + depositeamount; + * + * // Truncate the total amount to two decimal places + * //double truncatedTotalAmount = Math.floor(totalAmount * 100) / 100; + * // Round the total amount to two decimal places + * double truncatedTotalAmount = Math.round(totalAmount * 100.0) / 100.0; + * + * // Set the calculated amounts to bookingDetails + * bookingDetails.setDepositAmount(depositeamount); + * bookingDetails.setHallAmount(hallAmountforcentral); + * bookingDetails.setGst(gstAmount); + * bookingDetails.setAmountReceived(truncatedTotalAmount); + * hs.put("totalAmount", truncatedTotalAmount); + * } + */ else if (reasoncode.equals("CGE")) { if (startingSlot == 1 && endingSlot == 2) { discountAmount = (hallDetails.getFullDayRent() * hallDetails.getCGEdiscount()) / 100; hallAmount = hallDetails.getFullDayRent(); - hs.put("discount", hallDetails.getCGEdiscount()); // No discount for State Govt Event + hs.put("discount", hallDetails.getCGEdiscount()); // No discount for State Govt Event double cleaningCharges = governmentevents.getFullDayCleaningcharges(); double PASystem = governmentevents.getFulldayPAsystem(); double EB = governmentevents.getFulldayEBcharges(); @@ -867,7 +1000,7 @@ public String getBookingRefIdByBookingId(int bookingId) { double truncatedTotalAmount = Math.round(totalAmount * 100.0) / 100.0; hs.put("actualhallamount", hallAmount); bookingDetails.setDepositAmount(depositeamount); - //bookingDetails.setHallAmount(additionalcharges); + // bookingDetails.setHallAmount(additionalcharges); bookingDetails.setHallAmount(netAmount); bookingDetails.setGst(gstAmount); bookingDetails.setAmountReceived(truncatedTotalAmount); @@ -881,7 +1014,7 @@ public String getBookingRefIdByBookingId(int bookingId) { } else { discountAmount = (hallDetails.getHalfDayRent() * hallDetails.getCGEdiscount()) / 100; hallAmount = hallDetails.getHalfDayRent(); - hs.put("discount", hallDetails.getCGEdiscount()); // No discount for State Govt Event + hs.put("discount", hallDetails.getCGEdiscount()); // No discount for State Govt Event double cleaningCharges = governmentevents.getHalfDayCleaningcharges(); double PASystem = governmentevents.getHalfdayPAsystem(); double EB = governmentevents.getHalfdayEBcharges(); @@ -894,7 +1027,7 @@ public String getBookingRefIdByBookingId(int bookingId) { double truncatedTotalAmount = Math.round(totalAmount * 100.0) / 100.0; hs.put("actualhallamount", hallAmount); bookingDetails.setDepositAmount(depositeamount); - //bookingDetails.setHallAmount(additionalcharges); + // bookingDetails.setHallAmount(additionalcharges); bookingDetails.setHallAmount(netAmount); bookingDetails.setGst(gstAmount); bookingDetails.setAmountReceived(truncatedTotalAmount); @@ -908,7 +1041,6 @@ public String getBookingRefIdByBookingId(int bookingId) { } } - bookingDetails.setNoOfDays(days); bookingDetails.setStartingSlot(startingSlot); bookingDetails.setEndingSlot(endingSlot); @@ -932,17 +1064,24 @@ public String getBookingRefIdByBookingId(int bookingId) { BookingCalendar bookingCalendar = bookingCalendarRepository.findByBdateAndHallId(date, hallId); if (bookingCalendar != null) { - if ((date.equals(start) && bookingDetails.getStartingSlot() == 1 && bookingCalendar.isMorningSlot()) || - (date.equals(start) && bookingDetails.getStartingSlot() == 2 && bookingCalendar.isEveningSlot()) || - (date.equals(end) && bookingDetails.getEndingSlot() == 1 && bookingCalendar.isMorningSlot()) || - (date.equals(end) && bookingDetails.getEndingSlot() == 2 && bookingCalendar.isEveningSlot())) { + if ((date.equals(start) && bookingDetails.getStartingSlot() == 1 + && bookingCalendar.isMorningSlot()) || + (date.equals(start) && bookingDetails.getStartingSlot() == 2 + && bookingCalendar.isEveningSlot()) + || + (date.equals(end) && bookingDetails.getEndingSlot() == 1 + && bookingCalendar.isMorningSlot()) + || + (date.equals(end) && bookingDetails.getEndingSlot() == 2 + && bookingCalendar.isEveningSlot())) { return Collections.singletonMap("status", "slotOccupied"); } else if (bookingCalendar.isMorningSlot() && bookingCalendar.isEveningSlot()) { return Collections.singletonMap("status", "slotOccupied"); } else if (!date.equals(end) && i != 0 && i != Math.round(bookingDetails.getNoOfDays() - 1) && (bookingCalendar.isMorningSlot() || bookingCalendar.isEveningSlot())) { return Collections.singletonMap("status", "slotOccupied"); - } else if (date.equals(end) && bookingDetails.getEndingSlot() == 2 && bookingCalendar.isMorningSlot() + } else if (date.equals(end) && bookingDetails.getEndingSlot() == 2 + && bookingCalendar.isMorningSlot() && i != 0 && i == Math.round(bookingDetails.getNoOfDays() - 1)) { return Collections.singletonMap("status", "slotOccupied"); } @@ -984,8 +1123,10 @@ public String getBookingRefIdByBookingId(int bookingId) { } if (rm.isAddDocumentField()) { MultipartFile file = (MultipartFile) formData.get(rm.getDocFieldName()); - bd.setBookingDocUrl(serverPath + "images/" + reasonMaster.getReason() + "/" + bookingDetails.getBookingId() + "_" + file.getOriginalFilename()); - String filePath = uploadDirectory + "/" + reasonMaster.getReason() + "/" + bookingDetails.getBookingId() + "_" + file.getOriginalFilename(); + bd.setBookingDocUrl(serverPath + "images/" + reasonMaster.getReason() + "/" + + bookingDetails.getBookingId() + "_" + file.getOriginalFilename()); + String filePath = uploadDirectory + "/" + reasonMaster.getReason() + "/" + + bookingDetails.getBookingId() + "_" + file.getOriginalFilename(); bd.setDocumentName(file.getOriginalFilename()); bd.setDocumentType(file.getContentType()); @@ -1034,13 +1175,14 @@ public String getBookingRefIdByBookingId(int bookingId) { return hallAmount; } - public double calculateDepositAmount(double numDays, String startPeriod, String endPeriod, double depositAmount, double HalfDepositAmount) { + public double calculateDepositAmount(double numDays, String startPeriod, String endPeriod, double depositAmount, + double HalfDepositAmount) { double damount = 0; // FOR FULL DAY // If there is only one day - System.err.println("in calculate numDays..."+numDays); - System.err.println("in calculate depositAmount..."+depositAmount); - System.err.println("in calculate HalfDepositAmount..."+HalfDepositAmount); + System.err.println("in calculate numDays..." + numDays); + System.err.println("in calculate depositAmount..." + depositAmount); + System.err.println("in calculate HalfDepositAmount..." + HalfDepositAmount); if (numDays == 1) { if ("1".equals(startPeriod) && "2".equals(endPeriod)) { damount = depositAmount; @@ -1065,7 +1207,7 @@ public String getBookingRefIdByBookingId(int bookingId) { damount = numDays; } } - System.err.println("in calculate damount..."+damount); + System.err.println("in calculate damount..." + damount); return damount; } @@ -1081,7 +1223,7 @@ public String getBookingRefIdByBookingId(int bookingId) { // Ensure the directory exists File directory = new File(uploadDirectory + File.separator + reason); if (!directory.exists()) { - directory.mkdirs(); // Create the directory if it doesn't exist + directory.mkdirs(); // Create the directory if it doesn't exist } BookingHistory bookinghistory = new BookingHistory(); bookinghistory.setBookingStatus(bookingDetails.getBookingStatus()); @@ -1097,7 +1239,7 @@ public String getBookingRefIdByBookingId(int bookingId) { bd.setBookingDocUrl(fileUrl); bd.setDocumentName(file.getOriginalFilename()); bd.setDocumentType(file.getContentType()); - bd.setBookingDetails(bookingDetails); // Set the associated booking details + bd.setBookingDetails(bookingDetails); // Set the associated booking details bookingDetails.setBookingStatus(BookingStatus.WAITING_FOR_NOC_APPROVAL); bookingDetails.setComments("Waiting for Admin Approval"); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); @@ -1119,7 +1261,6 @@ public String getBookingRefIdByBookingId(int bookingId) { return "File uploaded and saved successfully"; } - @Transactional public List saveGCCBlockingDate(GccBlockingDate gcc) { // Save the GccBlockingDate first @@ -1148,8 +1289,10 @@ public String getBookingRefIdByBookingId(int bookingId) { bookingDetails.setDepositAmount(0); bookingDetails.setRefundStatus(BookingDetails.RefundStatus.NA); bookingDetails.setBookingDate(LocalDate.now()); - bookingDetails.setStartDate(LocalDate.ofInstant(savedGcc.getStartDate().toInstant(), ZoneId.systemDefault()).format(formatter)); - bookingDetails.setEndDate(LocalDate.ofInstant(savedGcc.getEndDate().toInstant(), ZoneId.systemDefault()).format(formatter)); + bookingDetails.setStartDate( + LocalDate.ofInstant(savedGcc.getStartDate().toInstant(), ZoneId.systemDefault()).format(formatter)); + bookingDetails.setEndDate( + LocalDate.ofInstant(savedGcc.getEndDate().toInstant(), ZoneId.systemDefault()).format(formatter)); bookingDetails.setHallAmount(0); bookingDetails.setHallDetails(hallDetails); bookingDetails.setUsers(user); @@ -1191,7 +1334,7 @@ public String getBookingRefIdByBookingId(int bookingId) { return data; } - //caretaker + // caretaker @Override public List getPresentsEventsByUserId(Integer hallId) { @@ -1231,8 +1374,7 @@ public String getBookingRefIdByBookingId(int bookingId) { BookingDetails save = bookingDetailsRepository.save(bookingDetails); return save; } - //carearetakerend - + // carearetakerend @Override public BookingDetails updateBookingStatusById(int bookingId, BookingDetails.BookingStatus status, String comments) { @@ -1249,7 +1391,8 @@ public String getBookingRefIdByBookingId(int bookingId) { } @Override - public BookingDetails updateCancelledBookingStatus(int bookingId, BookingDetails.BookingStatus status, String comments) { + public BookingDetails updateCancelledBookingStatus(int bookingId, BookingDetails.BookingStatus status, + String comments) { Optional bookingDetails = bookingDetailsRepository.findById(bookingId); if (bookingDetails.isPresent()) { BookingDetails bookDet = bookingDetails.get(); @@ -1272,7 +1415,8 @@ public String getBookingRefIdByBookingId(int bookingId) { String formattedDate = LocalDateTime.now().format(formatter); bookDet.setUpdatedDate(formattedDate); BookingDetails updatedBookingDetails = bookingDetailsRepository.save(bookDet); - List bookingCalendarList = bookingCalendarRepository.getCancellingdata1(String.valueOf(bookDet.getBookingId())); + List bookingCalendarList = bookingCalendarRepository + .getCancellingdata1(String.valueOf(bookDet.getBookingId())); for (BookingCalendar calendar : bookingCalendarList) { @@ -1289,7 +1433,7 @@ public String getBookingRefIdByBookingId(int bookingId) { } return updatedBookingDetails; } - //System.out.println("Booking details not found for ID: " + bookingId); + // System.out.println("Booking details not found for ID: " + bookingId); return null; } @@ -1329,20 +1473,25 @@ public String getBookingRefIdByBookingId(int bookingId) { Optional bd = bookingDetailsRepository.findById(bookingId); if (bd.isPresent()) { BookingDetails bookingDetails = bd.get(); - //System.out.println("currentStatus:-"+currentStatus); + // System.out.println("currentStatus:-"+currentStatus); if (bookingDetails.getBookingStatus().equals(BookingDetails.BookingStatus.APPROVED)) { - //System.err.println("test"+currentStatus); + // System.err.println("test"+currentStatus); if (currentStatus.equals(BookingDetails.BookingStatus.CANCELED)) { - //System.err.println("test11"+currentStatus); + // System.err.println("test11"+currentStatus); try { - //System.err.println("test13331==="+currentStatus); - applicationLogService.saveLog(bookingDetails.getBookingId(), ApplicationLogs.logsOfMsg.USER_CANCELLED_BOOKING.toString(), comments); - String refundTheDepositAmount = paymentGatewayService.refundTheDepositAmount(bookingDetails.getBookingId(), bookingDetails.getUsers().getUserId(), bookingDetails.getDepositAmount()); - //System.out.println("refundTheDepositAmount==="+refundTheDepositAmount); + // System.err.println("test13331==="+currentStatus); + applicationLogService.saveLog(bookingDetails.getBookingId(), + ApplicationLogs.logsOfMsg.USER_CANCELLED_BOOKING.toString(), comments); + String refundTheDepositAmount = paymentGatewayService.refundTheDepositAmount( + bookingDetails.getBookingId(), bookingDetails.getUsers().getUserId(), + bookingDetails.getDepositAmount()); + // System.out.println("refundTheDepositAmount==="+refundTheDepositAmount); if (refundTheDepositAmount.equals("Refunded")) { - updateBookingStatusById(bookingDetails.getBookingId(), BookingDetails.BookingStatus.CANCELED, "user cancelled Date:-" + new Date()); + updateBookingStatusById(bookingDetails.getBookingId(), + BookingDetails.BookingStatus.CANCELED, "user cancelled Date:-" + new Date()); - List bookingCalendarList = bookingCalendarRepository.getCancellingdata1(String.valueOf(bookingDetails.getBookingId())); + List bookingCalendarList = bookingCalendarRepository + .getCancellingdata1(String.valueOf(bookingDetails.getBookingId())); for (BookingCalendar calendar : bookingCalendarList) { boolean isUpdated = false; @@ -1377,13 +1526,17 @@ public String getBookingRefIdByBookingId(int bookingId) { } } else if (currentStatus.equals(BookingDetails.BookingStatus.REJECTED)) { try { - applicationLogService.saveLog(bookingDetails.getBookingId(), ApplicationLogs.logsOfMsg.GCC_REJECTED.toString(), comments); - String refundtheAmount = paymentGatewayService.refundTheAmount(bookingDetails.getBookingId(), bookingDetails.getUsers().getUserId()); - //System.out.println("refundtheAmount==="+refundtheAmount); + applicationLogService.saveLog(bookingDetails.getBookingId(), + ApplicationLogs.logsOfMsg.GCC_REJECTED.toString(), comments); + String refundtheAmount = paymentGatewayService.refundTheAmount(bookingDetails.getBookingId(), + bookingDetails.getUsers().getUserId()); + // System.out.println("refundtheAmount==="+refundtheAmount); if (refundtheAmount.equals("Refunded")) { - updateBookingStatusById(bookingDetails.getBookingId(), BookingDetails.BookingStatus.REJECTED, comments); + updateBookingStatusById(bookingDetails.getBookingId(), + BookingDetails.BookingStatus.REJECTED, comments); - List bookingCalendarList = bookingCalendarRepository.getCancellingdata1(String.valueOf(bookingDetails.getBookingId())); + List bookingCalendarList = bookingCalendarRepository + .getCancellingdata1(String.valueOf(bookingDetails.getBookingId())); for (BookingCalendar calendar : bookingCalendarList) { boolean isUpdated = false; @@ -1418,9 +1571,12 @@ public String getBookingRefIdByBookingId(int bookingId) { } } else if (currentStatus.equals(BookingDetails.BookingStatus.GCC_BLOCKED)) { try { - applicationLogService.saveLog(bookingDetails.getBookingId(), ApplicationLogs.logsOfMsg.GCC_BLOCKED_DATE.toString(), comments); - paymentGatewayService.refundTheAmount(bookingDetails.getBookingId(), bookingDetails.getUsers().getUserId()); - updateBookingStatusById(bookingDetails.getBookingId(), BookingDetails.BookingStatus.GCC_BLOCKED, "total amount will refund shortly"); + applicationLogService.saveLog(bookingDetails.getBookingId(), + ApplicationLogs.logsOfMsg.GCC_BLOCKED_DATE.toString(), comments); + paymentGatewayService.refundTheAmount(bookingDetails.getBookingId(), + bookingDetails.getUsers().getUserId()); + updateBookingStatusById(bookingDetails.getBookingId(), BookingDetails.BookingStatus.GCC_BLOCKED, + "total amount will refund shortly"); } catch (Exception e) { e.printStackTrace(); @@ -1428,180 +1584,191 @@ public String getBookingRefIdByBookingId(int bookingId) { } } - } return null; } - /*@Override + /* + * @Override + * public BookingDetails getBookingDetailsWithSettlement(int settlementId) { + * Optional SettleBookingDetails = + * Optional.of(bookingDetailsRepository.findBySettlementIdWithBookingDetails( + * settlementId)); + * if (SettleBookingDetails.isPresent()) { + * System.out.println("settlement list: " + SettleBookingDetails.get()); + * return SettleBookingDetails.get(); + * + * } + * return null; + * } + */ + // ak + /* + * @Override + * public BookingDetails getBookingDetailsWithSettlement(int settlementId) { + * // 🔹 Your existing logic (unchanged) + * Optional SettleBookingDetails = + * Optional.of(bookingDetailsRepository.findBySettlementIdWithBookingDetails( + * settlementId)); + * + * if (SettleBookingDetails.isPresent()) { + * BookingDetails bookingDetails = SettleBookingDetails.get(); + * System.out.println("settlement list: " + bookingDetails); + * + * // 🔹 Keep the same return behavior, but do reset before returning + * if (bookingDetails.getSettlement() == null) { + * Settlement settlement = bookingDetails.getSettlement(); + * + * // ✅ Auto-reset logic (only if approvedFlag=1 and approvedFlagDate != null) + * if (settlement.getApprovedFlag() == 1 && settlement.getApprovedFlagDate() != + * null) { + * long millisDiff = System.currentTimeMillis() - + * settlement.getApprovedFlagDate().getTime(); + * long daysDiff = millisDiff / (1000 * 60 * 60 * 24); + * + * System.out.println("Approved Flag Date: " + + * settlement.getApprovedFlagDate()); + * System.out.println("Current Java Date: " + new Date()); + * System.out.println("Days Difference: " + daysDiff); + * + * if (daysDiff >= 4) { + * settlement.setApprovedFlag(0); + * settlement.setApprovedFlagDate(null); + * settlementRepository.save(settlement); + * System.out.println("✅ Approved flag reset after 4 days for Settlement ID: " + + * settlement.getSettlementId()); + * } + * } + * } + * + * // ✅ Return same object (your original logic) + * return bookingDetails; + * } + * + * return null; + * } + */ + @Override + public List getSettlementInitiatedReport(String fromDate, String toDate) { + return bookingDetailsRepository.getSettlementInitiatedReport(fromDate, toDate); + } + + // ak + @Override public BookingDetails getBookingDetailsWithSettlement(int settlementId) { - Optional SettleBookingDetails = Optional.of(bookingDetailsRepository.findBySettlementIdWithBookingDetails(settlementId)); - if (SettleBookingDetails.isPresent()) { - System.out.println("settlement list: " + SettleBookingDetails.get()); - return SettleBookingDetails.get(); - - } - return null; - }*/ - //ak -/*@Override -public BookingDetails getBookingDetailsWithSettlement(int settlementId) { - // 🔹 Your existing logic (unchanged) - Optional SettleBookingDetails = - Optional.of(bookingDetailsRepository.findBySettlementIdWithBookingDetails(settlementId)); - - if (SettleBookingDetails.isPresent()) { - BookingDetails bookingDetails = SettleBookingDetails.get(); - System.out.println("settlement list: " + bookingDetails); - - // 🔹 Keep the same return behavior, but do reset before returning - if (bookingDetails.getSettlement() == null) { - Settlement settlement = bookingDetails.getSettlement(); - - // ✅ Auto-reset logic (only if approvedFlag=1 and approvedFlagDate != null) - if (settlement.getApprovedFlag() == 1 && settlement.getApprovedFlagDate() != null) { - long millisDiff = System.currentTimeMillis() - settlement.getApprovedFlagDate().getTime(); - long daysDiff = millisDiff / (1000 * 60 * 60 * 24); - - System.out.println("Approved Flag Date: " + settlement.getApprovedFlagDate()); - System.out.println("Current Java Date: " + new Date()); - System.out.println("Days Difference: " + daysDiff); - - if (daysDiff >= 4) { - settlement.setApprovedFlag(0); - settlement.setApprovedFlagDate(null); - settlementRepository.save(settlement); - System.out.println("✅ Approved flag reset after 4 days for Settlement ID: " + settlement.getSettlementId()); - } - } - } + // 🔹 Your existing logic (unchanged) + Optional SettleBookingDetails = Optional + .ofNullable(bookingDetailsRepository.findBySettlementIdWithBookingDetails(settlementId)); + // ak + /* + * Optional settlementOptional = + * settlementRepository.findById(settlementId); + * String adminname = (String) session.getAttribute("usertype"); + * if (settlementOptional.isPresent()) { + * Settlement settlement = settlementOptional.get(); + * + * SettlementHistory history = new SettlementHistory(); + * history.setSettlementId(settlement.getSettlementId()); + * history.setComments(settlement.getComments()); + * history.setCdate(settlement.getCdate()); + * history.setDamageAmount(settlement.getDamageAmount()); + * history.setEbAmount(settlement.getEbAmount()); + * history.setDepositAmount(settlement.getDepositAmount()); + * history.setRefundedAmount(settlement.getRefundedAmount()); + * history.setUpdatedDate(new Date()); + * history.setUpdatedId(adminname); + * history.setChallon(settlement.getChallon()); + * history.setDddate(settlement.getDddate()); + * history.setDdnumber(settlement.getDdnumber()); + * history.setBookingDetails(settlement.getBookingDetails()); + * history.setCollectionPending(settlement.getCollectionPending()); + * history.setDdamount(settlement.getDdamount()); + * history.setChallonnumber(settlement.getChallonnumber()); + * history.setCollectionStatus(settlement.getCollectionStatus()); + * history.setChallonamount(settlement.getChallonamount()); + * history.setApprovedFlag(settlement.getApprovedFlag()); + * history.setApprovedFlagDate(settlement.getApprovedFlagDate()); + * history.setShDate(new Date()); + * + * settlementHistoryRepository.save(history); + * System.out. + * println("✅ Record inserted into SettlementHistory for Settlement ID: " + + * settlementId); + * } + */ - // ✅ Return same object (your original logic) - return bookingDetails; - } + if (SettleBookingDetails.isPresent()) { + BookingDetails bookingDetails = SettleBookingDetails.get(); + System.out.println("settlement list: " + bookingDetails); + + // 🔹 Only do reset if settlement exists + if (bookingDetails.getSettlement() != null) { // ✅ FIXED HERE + Settlement settlement = bookingDetails.getSettlement(); + + // ✅ Auto-reset logic (only if approvedFlag=1 and approvedFlagDate != null) + if (settlement.getApprovedFlag() == 1 && settlement.getApprovedFlagDate() != null) { + long millisDiff = System.currentTimeMillis() - settlement.getApprovedFlagDate().getTime(); + long daysDiff = millisDiff / (1000 * 60 * 60 * 24); + + System.out.println("Approved Flag Date123: " + settlement.getApprovedFlagDate()); + System.out.println("Current Java Date: " + new Date()); + System.out.println("Days Difference: " + daysDiff); + + if (daysDiff > 4) { + // settlement histoty insert + Optional settlementOptional = settlementRepository.findById(settlementId); + String adminname = (String) session.getAttribute("usertype"); + if (settlementOptional.isPresent()) { + + SettlementHistory history = new SettlementHistory(); + history.setSettlementId(settlement.getSettlementId()); + history.setComments(settlement.getComments()); + history.setCdate(settlement.getCdate()); + history.setDamageAmount(settlement.getDamageAmount()); + history.setEbAmount(settlement.getEbAmount()); + history.setDepositAmount(settlement.getDepositAmount()); + history.setRefundedAmount(settlement.getRefundedAmount()); + history.setUpdatedDate(new Date()); + history.setUpdatedId(adminname); + history.setChallon(settlement.getChallon()); + history.setDddate(settlement.getDddate()); + history.setDdnumber(settlement.getDdnumber()); + history.setBookingDetails(settlement.getBookingDetails()); + history.setCollectionPending(settlement.getCollectionPending()); + history.setDdamount(settlement.getDdamount()); + history.setChallonnumber(settlement.getChallonnumber()); + history.setCollectionStatus(settlement.getCollectionStatus()); + history.setChallonamount(settlement.getChallonamount()); + history.setApprovedFlag(settlement.getApprovedFlag()); + history.setApprovedFlagDate(settlement.getApprovedFlagDate()); + history.setShDate(new Date()); + + settlementHistoryRepository.save(history); + System.out.println( + "✅ Record inserted into SettlementHistory for Settlement ID: " + settlementId); + } - return null; -}*/ -@Override -public List getSettlementInitiatedReport(String fromDate, String toDate) { - return bookingDetailsRepository.getSettlementInitiatedReport(fromDate, toDate); -} -//ak -@Override -public BookingDetails getBookingDetailsWithSettlement(int settlementId) { - // 🔹 Your existing logic (unchanged) - Optional SettleBookingDetails = - Optional.ofNullable(bookingDetailsRepository.findBySettlementIdWithBookingDetails(settlementId)); - //ak - /* Optional settlementOptional = settlementRepository.findById(settlementId); - String adminname = (String) session.getAttribute("usertype"); - if (settlementOptional.isPresent()) { - Settlement settlement = settlementOptional.get(); - - SettlementHistory history = new SettlementHistory(); - history.setSettlementId(settlement.getSettlementId()); - history.setComments(settlement.getComments()); - history.setCdate(settlement.getCdate()); - history.setDamageAmount(settlement.getDamageAmount()); - history.setEbAmount(settlement.getEbAmount()); - history.setDepositAmount(settlement.getDepositAmount()); - history.setRefundedAmount(settlement.getRefundedAmount()); - history.setUpdatedDate(new Date()); - history.setUpdatedId(adminname); - history.setChallon(settlement.getChallon()); - history.setDddate(settlement.getDddate()); - history.setDdnumber(settlement.getDdnumber()); - history.setBookingDetails(settlement.getBookingDetails()); - history.setCollectionPending(settlement.getCollectionPending()); - history.setDdamount(settlement.getDdamount()); - history.setChallonnumber(settlement.getChallonnumber()); - history.setCollectionStatus(settlement.getCollectionStatus()); - history.setChallonamount(settlement.getChallonamount()); - history.setApprovedFlag(settlement.getApprovedFlag()); - history.setApprovedFlagDate(settlement.getApprovedFlagDate()); - history.setShDate(new Date()); - - settlementHistoryRepository.save(history); - System.out.println("✅ Record inserted into SettlementHistory for Settlement ID: " + settlementId); - }*/ - - - - if (SettleBookingDetails.isPresent()) { - BookingDetails bookingDetails = SettleBookingDetails.get(); - System.out.println("settlement list: " + bookingDetails); - - - // 🔹 Only do reset if settlement exists - if (bookingDetails.getSettlement() != null) { // ✅ FIXED HERE - Settlement settlement = bookingDetails.getSettlement(); - - // ✅ Auto-reset logic (only if approvedFlag=1 and approvedFlagDate != null) - if (settlement.getApprovedFlag() == 1 && settlement.getApprovedFlagDate() != null) { - long millisDiff = System.currentTimeMillis() - settlement.getApprovedFlagDate().getTime(); - long daysDiff = millisDiff / (1000 * 60 * 60 * 24); - - System.out.println("Approved Flag Date123: " + settlement.getApprovedFlagDate()); - System.out.println("Current Java Date: " + new Date()); - System.out.println("Days Difference: " + daysDiff); - - if (daysDiff > 4) { - //settlement histoty insert - Optional settlementOptional = settlementRepository.findById(settlementId); - String adminname = (String) session.getAttribute("usertype"); - if (settlementOptional.isPresent()) { - - - SettlementHistory history = new SettlementHistory(); - history.setSettlementId(settlement.getSettlementId()); - history.setComments(settlement.getComments()); - history.setCdate(settlement.getCdate()); - history.setDamageAmount(settlement.getDamageAmount()); - history.setEbAmount(settlement.getEbAmount()); - history.setDepositAmount(settlement.getDepositAmount()); - history.setRefundedAmount(settlement.getRefundedAmount()); - history.setUpdatedDate(new Date()); - history.setUpdatedId(adminname); - history.setChallon(settlement.getChallon()); - history.setDddate(settlement.getDddate()); - history.setDdnumber(settlement.getDdnumber()); - history.setBookingDetails(settlement.getBookingDetails()); - history.setCollectionPending(settlement.getCollectionPending()); - history.setDdamount(settlement.getDdamount()); - history.setChallonnumber(settlement.getChallonnumber()); - history.setCollectionStatus(settlement.getCollectionStatus()); - history.setChallonamount(settlement.getChallonamount()); - history.setApprovedFlag(settlement.getApprovedFlag()); - history.setApprovedFlagDate(settlement.getApprovedFlagDate()); - history.setShDate(new Date()); - - settlementHistoryRepository.save(history); - System.out.println("✅ Record inserted into SettlementHistory for Settlement ID: " + settlementId); - } - - settlement.setApprovedFlag(0); - settlement.setApprovedFlagDate(null); - settlementRepository.save(settlement); - System.out.println("✅ Approved flag reset after 3 days for Settlement ID: " + settlement.getSettlementId()); + settlement.setApprovedFlag(0); + settlement.setApprovedFlagDate(null); + settlementRepository.save(settlement); + System.out.println("✅ Approved flag reset after 3 days for Settlement ID: " + + settlement.getSettlementId()); + } } + } else { + System.out.println("⚠️ No settlement found for booking ID: " + bookingDetails.getBookingId()); } - } else { - System.out.println("⚠️ No settlement found for booking ID: " + bookingDetails.getBookingId()); + + // ✅ Return same object (your original logic) + return bookingDetails; } - // ✅ Return same object (your original logic) - return bookingDetails; + return null; } - return null; -} - - - - @Override public BookingDetails saveebdetails(int bookingId, double startingReading, - MultipartFile startingReadingimage) { + MultipartFile startingReadingimage) { BookingDetails bd = getBookingsById(bookingId); if (bd != null) { if (bd.getEbDetails() == null) { @@ -1609,8 +1776,10 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { eb.setCdate(new Date()); eb.setStartingReading(startingReading); if (startingReadingimage != null) { - eb.setEbImageUrl((serverPath + "images/eb/" + bookingId + "_" + startingReadingimage.getOriginalFilename())); - String filePath = uploadDirectory + "/eb/" + bookingId + "_" + startingReadingimage.getOriginalFilename(); + eb.setEbImageUrl( + (serverPath + "images/eb/" + bookingId + "_" + startingReadingimage.getOriginalFilename())); + String filePath = uploadDirectory + "/eb/" + bookingId + "_" + + startingReadingimage.getOriginalFilename(); try (FileOutputStream fos = new FileOutputStream(filePath)) { byte[] bytes = startingReadingimage.getBytes(); fos.write(bytes); @@ -1628,8 +1797,8 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { @Override public String processEbDetailsAndDamage(int bookingId, int ebId, double startingReading, double endingReading, - float usedUnit, double ebAmount, String[] assetNames, String[] comments, int[] quantities, - Double[] assetAmounts, MultipartFile[] assetImages) { + float usedUnit, double ebAmount, String[] assetNames, String[] comments, int[] quantities, + Double[] assetAmounts, MultipartFile[] assetImages) { Optional findById = bookingDetailsRepository.findById(bookingId); if (findById.isPresent()) { BookingDetails book = findById.get(); @@ -1648,8 +1817,10 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { damage.setHallDetails(book.getHallDetails()); damageAmount = damageAmount + assetAmounts[i]; if (assetImages != null && !assetImages[i].isEmpty()) { - damage.setDamageImageUrl(serverPath + "images/damage/" + bookingId + "_" + assetImages[i].getOriginalFilename()); - String filePath = uploadDirectory + "/damage/" + bookingId + "_" + assetImages[i].getOriginalFilename(); + damage.setDamageImageUrl( + serverPath + "images/damage/" + bookingId + "_" + assetImages[i].getOriginalFilename()); + String filePath = uploadDirectory + "/damage/" + bookingId + "_" + + assetImages[i].getOriginalFilename(); try (FileOutputStream fos = new FileOutputStream(filePath)) { byte[] bytes = assetImages[i].getBytes(); fos.write(bytes); @@ -1691,7 +1862,7 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { return "Error"; } - //sreeja + // sreeja @Override public List getPastData(int hall_id) { List data = bookingCalendarRepository.getPastData(hall_id); @@ -1736,7 +1907,7 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { return bookingDetailsRepository.getAllBookingEventsByUserId(userId); } - //counter + // counter public List> getOfflineBookings() { return bookingDetailsRepository.findAllByBookingType(); } @@ -1746,35 +1917,37 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { return bookingCalendarRepository.findByHallIdAndDateRange(fromDate, endDate, hallIdList); } - // public List processRefundRequests(List bookingIds) { -// List bookIds = new ArrayList<>(); -// -// for (String bookingIdStr : bookingIds) { -// try { -// int bookingId = Integer.parseInt(bookingIdStr); -// Optional bookings = bookingDetailsRepository.findById(bookingId); -// if (bookings.isPresent()) { -// BookingDetails bookingDetails = bookings.get(); -// boolean refundSuccess = SettlementAmountRefund(bookingDetails); -// if (!refundSuccess) { -// bookIds.add(bookingIdStr); // Add ID to error list if refund fails -// } -// } else { -// bookIds.add(bookingIdStr); // Add ID to error list if booking not found -// } -// } catch (NumberFormatException e) { -// bookIds.add(bookingIdStr); // Add ID to error list if invalid format -// } catch (Exception e) { -// e.printStackTrace(); -// bookIds.add(bookingIdStr); // Add ID to error list for any other exception -// } -// } -// -// return bookIds; -// } -// private final ConcurrentHashMap processingMap = new ConcurrentHashMap<>(); -// -// @Synchronized + // public List processRefundRequests(List bookingIds) { + // List bookIds = new ArrayList<>(); + // + // for (String bookingIdStr : bookingIds) { + // try { + // int bookingId = Integer.parseInt(bookingIdStr); + // Optional bookings = + // bookingDetailsRepository.findById(bookingId); + // if (bookings.isPresent()) { + // BookingDetails bookingDetails = bookings.get(); + // boolean refundSuccess = SettlementAmountRefund(bookingDetails); + // if (!refundSuccess) { + // bookIds.add(bookingIdStr); // Add ID to error list if refund fails + // } + // } else { + // bookIds.add(bookingIdStr); // Add ID to error list if booking not found + // } + // } catch (NumberFormatException e) { + // bookIds.add(bookingIdStr); // Add ID to error list if invalid format + // } catch (Exception e) { + // e.printStackTrace(); + // bookIds.add(bookingIdStr); // Add ID to error list for any other exception + // } + // } + // + // return bookIds; + // } + // private final ConcurrentHashMap processingMap = new + // ConcurrentHashMap<>(); + // + // @Synchronized public String processRefundRequest(int bookingId) { try { Optional bookingOptional = bookingDetailsRepository.findById(bookingId); @@ -1795,19 +1968,23 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { } } - public boolean SettlementAmountRefund(BookingDetails bookingDetails) throws Exception { BookingStatus bookingStatus = bookingDetails.getBookingStatus(); RefundStatus refunStatus = bookingDetails.getRefundStatus(); String adminname = (String) session.getAttribute("usertype"); - if (bookingStatus == BookingStatus.APPROVED && !(refunStatus == RefundStatus.COMPLETED) && !(refunStatus == RefundStatus.CLOSED)) { - applicationLogService.saveLog(bookingDetails.getBookingId(), ApplicationLogs.logsOfMsg.SETTLEMENT_COMPLETED.toString(), "Refund will happen shortly"); - String refundThesettlementAmount = paymentGatewayService.refundTheDepositAmount(bookingDetails.getBookingId(), bookingDetails.getUsers().getUserId(), bookingDetails.getSettlement().getRefundedAmount()); - //System.out.println("refundThesettlementAmount === " + refundThesettlementAmount); + if (bookingStatus == BookingStatus.APPROVED && !(refunStatus == RefundStatus.COMPLETED) + && !(refunStatus == RefundStatus.CLOSED)) { + applicationLogService.saveLog(bookingDetails.getBookingId(), + ApplicationLogs.logsOfMsg.SETTLEMENT_COMPLETED.toString(), "Refund will happen shortly"); + String refundThesettlementAmount = paymentGatewayService.refundTheDepositAmount( + bookingDetails.getBookingId(), bookingDetails.getUsers().getUserId(), + bookingDetails.getSettlement().getRefundedAmount()); + // System.out.println("refundThesettlementAmount === " + + // refundThesettlementAmount); if (refundThesettlementAmount.equals("Refunded")) { Optional book = bookingDetailsRepository.findById(bookingDetails.getBookingId()); BookingDetails bookings = book.get(); - //bookinghistoty update + // bookinghistoty update BookingHistory bookingHistory = new BookingHistory(); bookingHistory.setStartDate(bookingDetails.getStartDate()); bookingHistory.setEndDate(bookingDetails.getEndDate()); @@ -1826,46 +2003,78 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { bookings.setUpdatedDate(formattedDate); bookings.setApprovedBy(adminname); bookingDetailsRepository.save(bookings); - String settlementrefundsms = "Your refund amount of Rs. " + bookings.getSettlement().getRefundedAmount() + " for Booking ID " + bookings.getBookingId() + " has been initiated. The amount will be credited to your account within 3 to 15 days. Thanks for using the GCC Community Hall Booking System."; - String settlementrefundurlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + bookings.getUsers().getMobileNo() + "&from=GCCCRP&body=" + settlementrefundsms + "&entityid=1401572690000011081&templateid=1407172346804951524"; - String settlementrefundwhatsupmsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + bookingDetails.getUsers().getMobileNo() + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+refund+of+Rs.+" + bookingDetails.getSettlement().getRefundedAmount() + "+for+Booking+ID+" + bookingDetails.getBookingId() + "+has+been+initiated.+%0AThe+amount+will+be+credited+to+your+account+within+3+to+15+days."; + String settlementrefundsms = "Your refund amount of Rs. " + bookings.getSettlement().getRefundedAmount() + + " for Booking ID " + bookings.getBookingId() + + " has been initiated. The amount will be credited to your account within 3 to 15 days. Thanks for using the GCC Community Hall Booking System."; + String settlementrefundurlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + + bookings.getUsers().getMobileNo() + "&from=GCCCRP&body=" + settlementrefundsms + + "&entityid=1401572690000011081&templateid=1407172346804951524"; + String settlementrefundwhatsupmsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + + bookingDetails.getUsers().getMobileNo() + + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+refund+of+Rs.+" + + bookingDetails.getSettlement().getRefundedAmount() + "+for+Booking+ID+" + + bookingDetails.getBookingId() + + "+has+been+initiated.+%0AThe+amount+will+be+credited+to+your+account+within+3+to+15+days."; whatsappMsgServiceImpl.sendMsg(settlementrefundwhatsupmsg); whatsappMsgServiceImpl.sendSMS(settlementrefundurlString); return true; } else { return false; } - } else if (bookingStatus == BookingStatus.REJECTED || bookingStatus == BookingStatus.GCC_BLOCKED && !(refunStatus == RefundStatus.COMPLETED) && !(refunStatus == RefundStatus.CLOSED)) { - applicationLogService.saveLog(bookingDetails.getBookingId(), ApplicationLogs.logsOfMsg.GCC_BLOCKED_DATE.toString(), "Refund will happen shortly"); - String refundFullAmount = paymentGatewayService.refundTheAmount(bookingDetails.getBookingId(), bookingDetails.getUsers().getUserId()); - //System.out.println("refundTheDepositAmount === " + refundFullAmount); + } else if (bookingStatus == BookingStatus.REJECTED || bookingStatus == BookingStatus.GCC_BLOCKED + && !(refunStatus == RefundStatus.COMPLETED) && !(refunStatus == RefundStatus.CLOSED)) { + applicationLogService.saveLog(bookingDetails.getBookingId(), + ApplicationLogs.logsOfMsg.GCC_BLOCKED_DATE.toString(), "Refund will happen shortly"); + String refundFullAmount = paymentGatewayService.refundTheAmount(bookingDetails.getBookingId(), + bookingDetails.getUsers().getUserId()); + // System.out.println("refundTheDepositAmount === " + refundFullAmount); if (refundFullAmount.equals("Refunded")) { Optional book = bookingDetailsRepository.findById(bookingDetails.getBookingId()); BookingDetails rejectedbookings = book.get(); rejectedbookings.setRefundStatus(RefundStatus.COMPLETED); bookingDetailsRepository.save(rejectedbookings); - String rejectedsms = "Your refund amount of Rs. " + rejectedbookings.getAmountReceived() + " for Booking ID " + rejectedbookings.getBookingId() + " has been initiated. The amount will be credited to your account within 3 to 15 days. Thanks for using the GCC Community Hall Booking System."; - String rejectedrefundurlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + rejectedbookings.getUsers().getMobileNo() + "&from=GCCCRP&body=" + rejectedsms + "&entityid=1401572690000011081&templateid=1407172346804951524"; - String settlementrefundwhatsupmsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + bookingDetails.getUsers().getMobileNo() + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+refund+of+Rs.+" + bookingDetails.getAmountReceived() + "+for+Booking+ID+" + bookingDetails.getBookingId() + "+has+been+initiated.+%0AThe+amount+will+be+credited+to+your+account+within+3+to+15+days."; + String rejectedsms = "Your refund amount of Rs. " + rejectedbookings.getAmountReceived() + + " for Booking ID " + rejectedbookings.getBookingId() + + " has been initiated. The amount will be credited to your account within 3 to 15 days. Thanks for using the GCC Community Hall Booking System."; + String rejectedrefundurlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + + rejectedbookings.getUsers().getMobileNo() + "&from=GCCCRP&body=" + rejectedsms + + "&entityid=1401572690000011081&templateid=1407172346804951524"; + String settlementrefundwhatsupmsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + + bookingDetails.getUsers().getMobileNo() + + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+refund+of+Rs.+" + + bookingDetails.getAmountReceived() + "+for+Booking+ID+" + bookingDetails.getBookingId() + + "+has+been+initiated.+%0AThe+amount+will+be+credited+to+your+account+within+3+to+15+days."; whatsappMsgServiceImpl.sendMsg(settlementrefundwhatsupmsg); whatsappMsgServiceImpl.sendSMS(rejectedrefundurlString); return true; } else { return false; } - } else if (bookingStatus == BookingStatus.CANCELED && !(refunStatus == RefundStatus.COMPLETED) && !(refunStatus == RefundStatus.CLOSED)) { - // System.out.println("Booking status is Cancelled. Booking ID: " + bookingDetails.getBookingId()); - applicationLogService.saveLog(bookingDetails.getBookingId(), ApplicationLogs.logsOfMsg.USER_CANCELLED_BOOKING.toString(), "Refund will happen shortly"); - String refundTheDepositAmount = paymentGatewayService.refundTheDepositAmount(bookingDetails.getBookingId(), bookingDetails.getUsers().getUserId(), bookingDetails.getDepositAmount()); - //System.out.println("refundTheDepositAmount === " + refundTheDepositAmount); + } else if (bookingStatus == BookingStatus.CANCELED && !(refunStatus == RefundStatus.COMPLETED) + && !(refunStatus == RefundStatus.CLOSED)) { + // System.out.println("Booking status is Cancelled. Booking ID: " + + // bookingDetails.getBookingId()); + applicationLogService.saveLog(bookingDetails.getBookingId(), + ApplicationLogs.logsOfMsg.USER_CANCELLED_BOOKING.toString(), "Refund will happen shortly"); + String refundTheDepositAmount = paymentGatewayService.refundTheDepositAmount(bookingDetails.getBookingId(), + bookingDetails.getUsers().getUserId(), bookingDetails.getDepositAmount()); + // System.out.println("refundTheDepositAmount === " + refundTheDepositAmount); if (refundTheDepositAmount.equals("Refunded")) { Optional book = bookingDetailsRepository.findById(bookingDetails.getBookingId()); BookingDetails cancelledbookings = book.get(); cancelledbookings.setRefundStatus(RefundStatus.COMPLETED); bookingDetailsRepository.save(cancelledbookings); - String cancelledsms = "Your refund amount of Rs. " + cancelledbookings.getDepositAmount() + " for Booking ID " + cancelledbookings.getBookingId() + " has been initiated. The amount will be credited to your account within 3 to 15 days. Thanks for using the GCC Community Hall Booking System."; - String cancelledrefundurlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + cancelledbookings.getUsers().getMobileNo() + "&from=GCCCRP&body=" + cancelledsms + "&entityid=1401572690000011081&templateid=1407172346804951524"; - String settlementrefundwhatsupmsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + bookingDetails.getUsers().getMobileNo() + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+refund+of+Rs.+" + bookingDetails.getDepositAmount() + "+for+Booking+ID+" + bookingDetails.getBookingId() + "+has+been+initiated.+%0AThe+amount+will+be+credited+to+your+account+within+3+to+15+days."; + String cancelledsms = "Your refund amount of Rs. " + cancelledbookings.getDepositAmount() + + " for Booking ID " + cancelledbookings.getBookingId() + + " has been initiated. The amount will be credited to your account within 3 to 15 days. Thanks for using the GCC Community Hall Booking System."; + String cancelledrefundurlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + + cancelledbookings.getUsers().getMobileNo() + "&from=GCCCRP&body=" + cancelledsms + + "&entityid=1401572690000011081&templateid=1407172346804951524"; + String settlementrefundwhatsupmsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + + bookingDetails.getUsers().getMobileNo() + + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+refund+of+Rs.+" + + bookingDetails.getDepositAmount() + "+for+Booking+ID+" + bookingDetails.getBookingId() + + "+has+been+initiated.+%0AThe+amount+will+be+credited+to+your+account+within+3+to+15+days."; whatsappMsgServiceImpl.sendMsg(settlementrefundwhatsupmsg); whatsappMsgServiceImpl.sendSMS(cancelledrefundurlString); return true; @@ -1892,7 +2101,7 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { bookingHistory.setBookingStatus(book.getBookingStatus()); bookingHistory.setUpdatedBy(adminname); bookingHistory.setCdate(new Date()); - bookingHistory.setRefundStatus(book.getRefundStatus()); + bookingHistory.setRefundStatus(book.getRefundStatus()); bookingHistoryRepository.save(bookingHistory); book.setComments("Refund status Updated to:-" + status); @@ -1902,15 +2111,15 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { return null; } - //officer reports + // officer reports @Override public List getAllBookingDetailsByZone(String fromDate, String toDate, String zone) { return bookingDetailsRepository.getAllBookingDetailsByZone(fromDate, toDate, zone); } - @Override - public List getAllBookingDetailsByZoneWithStatus(String fromDate, String toDate, String zone, String bookingStatus) { + public List getAllBookingDetailsByZoneWithStatus(String fromDate, String toDate, String zone, + String bookingStatus) { return bookingDetailsRepository.getAllBookingDetailsByZoneWithStatus(fromDate, toDate, zone, bookingStatus); } @@ -1924,11 +2133,12 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { return bookingDetailsRepository.getBookingHallDetailsReportByZone(fromDate, toDate, zone); } - //R + // R @Transactional public Optional updateBookingDatesAndCalendar(int bookingId, String startDat, String endDat) { Optional optionalBookingDetails = bookingDetailsRepository.findById(bookingId); - //TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition()); + // TransactionStatus status = transactionManager.getTransaction(new + // DefaultTransactionDefinition()); if (optionalBookingDetails.isPresent()) { BookingDetails bookingDetails = optionalBookingDetails.get(); String starting = bookingDetails.getStartDate(); @@ -1937,11 +2147,12 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { LocalDate startDate = LocalDate.parse(startDat, formatter); LocalDate endDate = LocalDate.parse(endDat, formatter); - // Retrieve existing calendar entries where bookingId matches booking_id1 or booking_id2 - List existingCalendars = bookingCalendarRepository.getCancellingdata1(String.valueOf(bookingId)); + // Retrieve existing calendar entries where bookingId matches booking_id1 or + // booking_id2 + List existingCalendars = bookingCalendarRepository + .getCancellingdata1(String.valueOf(bookingId)); - -// Empty the existing date in calendar + // Empty the existing date in calendar for (BookingCalendar calendar : existingCalendars) { if (calendar.getBookingId_1() != null && calendar.getBookingId_1().equals(String.valueOf(bookingId))) { calendar.setMorningSlot(false); @@ -1954,7 +2165,6 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { bookingCalendarRepository.save(calendar); } - // Check if the dates exist and update or create new entries accordingly String slotOccExpMsg = "Dates are already occupied. Please select another date."; int i = 0; @@ -1962,10 +2172,16 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { BookingCalendar bookingCalendar = bookingCalendarRepository.findByBdateAndHallId(date, hallId); if (bookingCalendar != null) { // Check if the slot is already occupied - if ((date.equals(startDate) && bookingDetails.getStartingSlot() == 1 && bookingCalendar.isMorningSlot()) || - (date.equals(startDate) && bookingDetails.getStartingSlot() == 2 && bookingCalendar.isEveningSlot()) || - (date.equals(endDate) && bookingDetails.getEndingSlot() == 1 && bookingCalendar.isMorningSlot()) || - (date.equals(endDate) && bookingDetails.getEndingSlot() == 2 && bookingCalendar.isEveningSlot())) { + if ((date.equals(startDate) && bookingDetails.getStartingSlot() == 1 + && bookingCalendar.isMorningSlot()) || + (date.equals(startDate) && bookingDetails.getStartingSlot() == 2 + && bookingCalendar.isEveningSlot()) + || + (date.equals(endDate) && bookingDetails.getEndingSlot() == 1 + && bookingCalendar.isMorningSlot()) + || + (date.equals(endDate) && bookingDetails.getEndingSlot() == 2 + && bookingCalendar.isEveningSlot())) { // return "Slot occupied"; throw new SlotOccupiedException(slotOccExpMsg); @@ -1976,15 +2192,17 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { } else if (!date.equals(endDate) && i != 0 && i != Math.round(bookingDetails.getNoOfDays() - 1) && (bookingCalendar.isMorningSlot() || bookingCalendar.isEveningSlot())) { - //System.out.println("booking slot occupied:- 227 :-"+Math.round(bookingDetails.getNoOfDays()-1) ); + // System.out.println("booking slot occupied:- 227 + // :-"+Math.round(bookingDetails.getNoOfDays()-1) ); throw new SlotOccupiedException(slotOccExpMsg); - } else if (date.equals(endDate) && bookingDetails.getEndingSlot() == 2 && bookingCalendar.isMorningSlot() + } else if (date.equals(endDate) && bookingDetails.getEndingSlot() == 2 + && bookingCalendar.isMorningSlot() && i != 0 && i == Math.round(bookingDetails.getNoOfDays() - 1)) { - // System.out.println("booking slot occupied:- 240 :-"+Math.round(bookingDetails.getNoOfDays()-1) ); + // System.out.println("booking slot occupied:- 240 + // :-"+Math.round(bookingDetails.getNoOfDays()-1) ); throw new SlotOccupiedException(slotOccExpMsg); } - } else { String uniqueId = date.format(DateTimeFormatter.ofPattern("yyyyMMdd")) + hallId; bookingCalendar = new BookingCalendar(); @@ -2005,7 +2223,8 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { bookingCalendar.setEveningSlot(true); bookingCalendar.setBookingId_2(String.valueOf(bookingId)); bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1); - } else if (startDate.equals(endDate) && bookingDetails.getStartingSlot() == 1 && bookingDetails.getEndingSlot() == 2) { + } else if (startDate.equals(endDate) && bookingDetails.getStartingSlot() == 1 + && bookingDetails.getEndingSlot() == 2) { bookingCalendar.setEveningSlot(true); bookingCalendar.setBookingId_2(String.valueOf(bookingId)); bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1); @@ -2043,12 +2262,20 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { bookingCalendarRepository.save(bookingCalendar); i++; } - //transactionManager.rollback(status); + // transactionManager.rollback(status); updateResheduledBookingDetails(bookingId, startDat, endDat); - String rescheduledmsg = "Your booking ID " + bookingId + " on " + starting + " has been successfully rescheduled to " + startDate + ". Thanks for using the GCC Community Hall Booking System."; - String urlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + bookingDetails.getUsers().getMobileNo() + "&from=GCCCRP&body=" + rescheduledmsg + "&entityid=1401572690000011081&templateid=1407172346565044999"; - String rescheduleMsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + bookingDetails.getUsers().getMobileNo() + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+booking+with+ID+" + bookingId + "+on+" + starting + "+has+been+successfully+rescheduled+to+" + startDate + "+.+%0AThank+you+for+using+the+GCC+Community+Hall+Booking+System."; + String rescheduledmsg = "Your booking ID " + bookingId + " on " + starting + + " has been successfully rescheduled to " + startDate + + ". Thanks for using the GCC Community Hall Booking System."; + String urlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + + bookingDetails.getUsers().getMobileNo() + "&from=GCCCRP&body=" + rescheduledmsg + + "&entityid=1401572690000011081&templateid=1407172346565044999"; + String rescheduleMsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + + bookingDetails.getUsers().getMobileNo() + + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+booking+with+ID+" + bookingId + + "+on+" + starting + "+has+been+successfully+rescheduled+to+" + startDate + + "+.+%0AThank+you+for+using+the+GCC+Community+Hall+Booking+System."; whatsappMsgServiceImpl.sendMsg(rescheduleMsg); whatsappMsgServiceImpl.sendSMS(urlString); return Optional.of("Booking dates updated successfully."); @@ -2063,7 +2290,7 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { if (bookingDetails.getReason().equals("Commercial")) { bookingDetails.setBookingStatus(BookingStatus.WAITING_FOR_NOC); } - //Updating Bookinghistory startDate and End Date + // Updating Bookinghistory startDate and End Date BookingHistory bookingHistory = new BookingHistory(); bookingHistory.setStartDate(bookingDetails.getStartDate()); bookingHistory.setEndDate(bookingDetails.getEndDate()); @@ -2084,7 +2311,8 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { } @Override - public List getBookingHallDetailsReportByZone1(String fromDate, String toDate, String zone, Integer hallId) { + public List getBookingHallDetailsReportByZone1(String fromDate, String toDate, String zone, + Integer hallId) { // TODO Auto-generated method stub return bookingDetailsRepository.getBookingHallDetailsReportByZone1(fromDate, toDate, zone, hallId); } @@ -2094,10 +2322,12 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { .orElseThrow(() -> new RuntimeException("Hall not found")); // Fetch BookingDetails with GCC_BLOCKED status - List bookingDetails = bookingDetailsRepository.findByHallDetailsAndBookingStatus(hallDetails, BookingDetails.BookingStatus.GCC_BLOCKED); + List bookingDetails = bookingDetailsRepository.findByHallDetailsAndBookingStatus(hallDetails, + BookingDetails.BookingStatus.GCC_BLOCKED); // Fetch GccBlockingDate with BLOCKED status - List gccBlockingDates = gccBlockingDateRepository.findAllByHallIdAndBlockedStatus(hallId, GccBlockingDate.BlockedStatus.BLOCKED); + List gccBlockingDates = gccBlockingDateRepository.findAllByHallIdAndBlockedStatus(hallId, + GccBlockingDate.BlockedStatus.BLOCKED); // Combine results into a list of Object (can be more specific if needed) List results = new ArrayList<>(); @@ -2115,13 +2345,15 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { public boolean isBlockingRecordExists(String fromDate, String toDate, List hallIdsList) { LocalDate fromdate = LocalDate.parse(fromDate); LocalDate todate = LocalDate.parse(toDate); - List existingRecords = gccBlockingDateRepository.findByFromDateAndToDateBetweenAndHallIdIn(fromdate, todate, hallIdsList); + List existingRecords = gccBlockingDateRepository + .findByFromDateAndToDateBetweenAndHallIdIn(fromdate, todate, hallIdsList); return !existingRecords.isEmpty(); } @Override public void cancelAllBookings(String fromDate, String toDate, List hallIdsList, - String reasonforblocking, List selectedBookings, String updatedBy, String[] descriptions, MultipartFile[] documents) { + String reasonforblocking, List selectedBookings, String updatedBy, String[] descriptions, + MultipartFile[] documents) { if (selectedBookings != null && !selectedBookings.isEmpty()) { for (String bookingIdStr : selectedBookings) { Integer bookingId = Integer.parseInt(bookingIdStr); @@ -2146,7 +2378,7 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { bb.setBookingId_2(null); bb.setEveningSlot(false); } - //bb.setIs_blocked(true); + // bb.setIs_blocked(true); updateBookingStatus(bb); } @@ -2154,15 +2386,19 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { GccBlockingDate gcc = new GccBlockingDate(); gcc.setStartDate(convertStringToDate(fromDate)); gcc.setEndDate(convertStringToDate(toDate)); - gcc.setHallId(String.join(",", hallIdsList.stream().map(String::valueOf).collect(Collectors.toList()))); + gcc.setHallId(String.join(",", + hallIdsList.stream().map(String::valueOf).collect(Collectors.toList()))); gcc.setUpdatedBy(updatedBy); gcc.setCdate(new Date()); gcc.setBlockingReason(reasonforblocking); - if (documents != null && documents.length > 0 && descriptions != null && descriptions.length > 0) { + if (documents != null && documents.length > 0 && descriptions != null + && descriptions.length > 0) { int i = 0; for (MultipartFile document : documents) { - String filePath = uploadDirectory + "/" + gcc.getBlockingId() + "_" + i + "_" + document.getOriginalFilename(); - String documentUrl = serverPath + "gccblockingdocs/" + gcc.getBlockingId() + "_" + i + "_" + document.getOriginalFilename(); + String filePath = uploadDirectory + "/" + gcc.getBlockingId() + "_" + i + "_" + + document.getOriginalFilename(); + String documentUrl = serverPath + "gccblockingdocs/" + gcc.getBlockingId() + "_" + i + + "_" + document.getOriginalFilename(); try (FileOutputStream fos = new FileOutputStream(filePath)) { // Save document to the file system @@ -2170,11 +2406,17 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { fos.write(bytes); // Save document details along with description in the database - GccblockingDocuments documentDetails = new GccblockingDocuments(); // Assuming you have a DocumentDetails entity - documentDetails.setBlockingDate(gcc); // Assuming hallDetails is associated with the document - documentDetails.setBlockingDocument(documentUrl); // Save the URL of the uploaded document - documentDetails.setDescription(descriptions[i]); // Save corresponding description - gccblockingDocumentsRepo.save(documentDetails); // Save the document and description in the database + GccblockingDocuments documentDetails = new GccblockingDocuments(); // Assuming you + // have a + // DocumentDetails + // entity + documentDetails.setBlockingDate(gcc); // Assuming hallDetails is associated with the + // document + documentDetails.setBlockingDocument(documentUrl); // Save the URL of the uploaded + // document + documentDetails.setDescription(descriptions[i]); // Save corresponding description + gccblockingDocumentsRepo.save(documentDetails); // Save the document and description + // in the database } catch (IOException e) { throw new RuntimeException("Failed to save document", e); } @@ -2182,12 +2424,12 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { } } - // GCC blocking History GccBlockingHistory gccblockinghistory = new GccBlockingHistory(); gccblockinghistory.setStartDate(convertStringToDate(fromDate)); gccblockinghistory.setEndDate(convertStringToDate(toDate)); - gccblockinghistory.setHallId(String.join(",", hallIdsList.stream().map(String::valueOf).collect(Collectors.toList()))); + gccblockinghistory.setHallId(String.join(",", + hallIdsList.stream().map(String::valueOf).collect(Collectors.toList()))); gccblockinghistory.setUpdatedBy(updatedBy); gccblockinghistory.setCdate(new Date()); gccblockinghistory.setBlockingReason(reasonforblocking); @@ -2206,7 +2448,7 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { BookingCalendar data = getbyDates(aa, hallId.toString()); int userbookingbookingId = bookingIds.get(hallIdsList.indexOf(hallId)); if (data != null) { - System.out.println("uniqueId...1"+uniqueId); + System.out.println("uniqueId...1" + uniqueId); data.setBookingId_1(String.valueOf(userbookingbookingId)); data.setBookingId_2(String.valueOf(userbookingbookingId)); data.setMorningSlot(true); @@ -2215,7 +2457,7 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { data.setUnique_id(uniqueId); updateBookingStatus(data); } else { - System.out.println("uniqueId...2"+uniqueId); + System.out.println("uniqueId...2" + uniqueId); BookingCalendar book = new BookingCalendar(); book.setBdate(aa); book.setBookingId_1(String.valueOf(userbookingbookingId)); @@ -2233,12 +2475,22 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { } } - updateBookingStatusById(booking.getBookingId(), booking.getBookingStatus().GCC_BLOCKED, reasonforblocking); - //whatsup msg and SMS - String gccblockedsms = "Your booking ID " + bookingId + " on " + booking.getStartDate() + " has been blocked by GCC due to " + reasonforblocking + ". The entire amount paid will be refunded to your account with in 3 to 15 days."; - String gccblockedurlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + booking.getUsers().getMobileNo() + "&from=GCCCRP&body=" + gccblockedsms + "&entityid=1401572690000011081&templateid=1407172346521513227"; - //String gccblockedwhatsupmsg="https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to="+booking.getUsers().getMobileNo()+"&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+booking+with+ID+"+booking.getBookingId()+"+on+"+booking.getBookingDate()+"+has+been+blocked+by+GCC+due+to+"+reasonforblocking+".+%0AThanks+for+using+GCC+Community+Hall+Booking+System."; - String gccblockedwhatsupmsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + booking.getUsers().getMobileNo() + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+booking+with+ID+" + booking.getBookingId() + "+on+" + booking.getStartDate() + "+has+been+blocked+by+the+GCC+due+to+Goverment+event++.+%0AThe+entire+amount+paid+will+be+refunded+to+your+account+within+3+to+15+days."; + updateBookingStatusById(booking.getBookingId(), booking.getBookingStatus().GCC_BLOCKED, + reasonforblocking); + // whatsup msg and SMS + String gccblockedsms = "Your booking ID " + bookingId + " on " + booking.getStartDate() + + " has been blocked by GCC due to " + reasonforblocking + + ". The entire amount paid will be refunded to your account with in 3 to 15 days."; + String gccblockedurlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + + booking.getUsers().getMobileNo() + "&from=GCCCRP&body=" + gccblockedsms + + "&entityid=1401572690000011081&templateid=1407172346521513227"; + // String + // gccblockedwhatsupmsg="https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to="+booking.getUsers().getMobileNo()+"&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+booking+with+ID+"+booking.getBookingId()+"+on+"+booking.getBookingDate()+"+has+been+blocked+by+GCC+due+to+"+reasonforblocking+".+%0AThanks+for+using+GCC+Community+Hall+Booking+System."; + String gccblockedwhatsupmsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + + booking.getUsers().getMobileNo() + + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+booking+with+ID+" + + booking.getBookingId() + "+on+" + booking.getStartDate() + + "+has+been+blocked+by+the+GCC+due+to+Goverment+event++.+%0AThe+entire+amount+paid+will+be+refunded+to+your+account+within+3+to+15+days."; whatsappMsgServiceImpl.sendMsg(gccblockedwhatsupmsg); whatsappMsgServiceImpl.sendSMS(gccblockedurlString); bookingDetailsRepository.save(booking); @@ -2257,7 +2509,8 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { GccBlockingHistory gccblockinghistory = new GccBlockingHistory(); gccblockinghistory.setStartDate(convertStringToDate(fromDate)); gccblockinghistory.setEndDate(convertStringToDate(toDate)); - gccblockinghistory.setHallId(String.join(",", hallIdsList.stream().map(String::valueOf).collect(Collectors.toList()))); + gccblockinghistory.setHallId( + String.join(",", hallIdsList.stream().map(String::valueOf).collect(Collectors.toList()))); gccblockinghistory.setUpdatedBy(updatedBy); gccblockinghistory.setCdate(new Date()); gccblockinghistory.setBlockingReason(reasonforblocking); @@ -2271,8 +2524,10 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { if (descriptions != null && descriptions.length == documents.length) { int i = 0; for (MultipartFile document : documents) { - String filePath = uploadDirectory + "/" + gcc.getBlockingId() + "_" + i + "_" + document.getOriginalFilename(); - String documentUrl = serverPath + "gccblockingdocs/" + gcc.getBlockingId() + "_" + i + "_" + document.getOriginalFilename(); + String filePath = uploadDirectory + "/" + gcc.getBlockingId() + "_" + i + "_" + + document.getOriginalFilename(); + String documentUrl = serverPath + "gccblockingdocs/" + gcc.getBlockingId() + "_" + i + "_" + + document.getOriginalFilename(); try (FileOutputStream fos = new FileOutputStream(filePath)) { byte[] bytes = document.getBytes(); @@ -2303,7 +2558,7 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { String uniqueId = date.format(DateTimeFormatter.ofPattern("yyyyMMdd")) + hallId; int userbookingbookingId = bookingIds.get(hallIdsList.indexOf(hallId)); if (data != null) { - System.out.println("uniqueId...11"+uniqueId); + System.out.println("uniqueId...11" + uniqueId); data.setBookingId_1(String.valueOf(userbookingbookingId)); data.setBookingId_2(String.valueOf(userbookingbookingId)); data.setMorningSlot(true); @@ -2312,7 +2567,7 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { data.setUnique_id(uniqueId); updateBookingStatus(data); } else { - System.out.println("uniqueId...21"+uniqueId); + System.out.println("uniqueId...21" + uniqueId); BookingCalendar book = new BookingCalendar(); book.setBdate(date); book.setBookingId_1(String.valueOf(userbookingbookingId)); @@ -2358,10 +2613,12 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { return bookingDetailsRepository.findBookingDetailsByBookingId(bookingId); } - //admin dashboard + // admin dashboard @Override - public Map> getBookingStatistics(LocalDate fromDate, LocalDate toDate, String zone, String division, Integer hallid, String userType) { - List> rawStatistics = bookingDetailsRepository.getBookingStatistics(fromDate, toDate, zone, division, hallid, userType); + public Map> getBookingStatistics(LocalDate fromDate, LocalDate toDate, String zone, + String division, Integer hallid, String userType) { + List> rawStatistics = bookingDetailsRepository.getBookingStatistics(fromDate, toDate, zone, + division, hallid, userType); return transformData(rawStatistics); } @@ -2369,7 +2626,8 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { Map> transformedData = new HashMap<>(); for (Map entry : rawStatistics) { - if (entry.isEmpty()) continue; // Skip empty entries + if (entry.isEmpty()) + continue; // Skip empty entries String category = (String) entry.get("category"); String key = entry.get("key") != null ? (String) entry.get("key") : "total"; @@ -2379,18 +2637,29 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { transformedData.get(category).put(key, totalCount); if (category.equals("main")) { - Integer mainTotalAmount = entry.get("main_total_amount") != null ? ((Number) entry.get("main_total_amount")).intValue() : 0; - Integer mainRefundedAmount = entry.get("main_refunded_amount") != null ? ((Number) entry.get("main_refunded_amount")).intValue() : 0; - Integer mainNetAmount = entry.get("main_net_amount") != null ? ((Number) entry.get("main_net_amount")).intValue() : 0; - Integer mainGstAmount = entry.get("main_gst_amount") != null ? ((Number) entry.get("main_gst_amount")).intValue() : 0; + Integer mainTotalAmount = entry.get("main_total_amount") != null + ? ((Number) entry.get("main_total_amount")).intValue() + : 0; + Integer mainRefundedAmount = entry.get("main_refunded_amount") != null + ? ((Number) entry.get("main_refunded_amount")).intValue() + : 0; + Integer mainNetAmount = entry.get("main_net_amount") != null + ? ((Number) entry.get("main_net_amount")).intValue() + : 0; + Integer mainGstAmount = entry.get("main_gst_amount") != null + ? ((Number) entry.get("main_gst_amount")).intValue() + : 0; transformedData.get(category).put("main_total_amount", mainTotalAmount); transformedData.get(category).put("main_net_amount", mainNetAmount); transformedData.get(category).put("main_refunded_amount", mainRefundedAmount); transformedData.get(category).put("main_gst_amount", mainGstAmount); } if (category.equals("past_future")) { - Integer pastbooking = entry.get("PAST_Events") != null ? ((Number) entry.get("PAST_Events")).intValue() : 0; - Integer futurebooking = entry.get("FUTURE_Events") != null ? ((Number) entry.get("FUTURE_Events")).intValue() : 0; + Integer pastbooking = entry.get("PAST_Events") != null ? ((Number) entry.get("PAST_Events")).intValue() + : 0; + Integer futurebooking = entry.get("FUTURE_Events") != null + ? ((Number) entry.get("FUTURE_Events")).intValue() + : 0; transformedData.get(category).put("PAST_Events", pastbooking); transformedData.get(category).put("FUTURE_Events", futurebooking); } @@ -2402,11 +2671,13 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { public List> getBookingDetailsByHallId(int hallId) { return bookingDetailsRepository.getBookingDetailsByHallId(hallId); } - //officer Dashboard + // officer Dashboard @Override - public Map> getOfficerDashboard(LocalDate fromDate, LocalDate toDate, String zone, String division, Integer hallid, String userType) { - List> rawStatistics = bookingDetailsRepository.getOfficerDashboard(fromDate, toDate, zone, division, hallid, userType); + public Map> getOfficerDashboard(LocalDate fromDate, LocalDate toDate, String zone, + String division, Integer hallid, String userType) { + List> rawStatistics = bookingDetailsRepository.getOfficerDashboard(fromDate, toDate, zone, + division, hallid, userType); return transformedData(rawStatistics); } @@ -2414,7 +2685,8 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { Map> transformedData = new HashMap<>(); for (Map entry : rawStatistics) { - if (entry.isEmpty()) continue; // Skip empty entries + if (entry.isEmpty()) + continue; // Skip empty entries String category = (String) entry.get("category"); String key = entry.get("key") != null ? (String) entry.get("key") : "total"; @@ -2424,16 +2696,25 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { transformedData.get(category).put(key, totalCount); if (category.equals("main")) { - Integer mainTotalAmount = entry.get("main_total_amount") != null ? ((Number) entry.get("main_total_amount")).intValue() : 0; - Integer mainNetAmount = entry.get("main_net_amount") != null ? ((Number) entry.get("main_net_amount")).intValue() : 0; - Integer mainRefundedAmount = entry.get("main_refunded_amount") != null ? ((Number) entry.get("main_refunded_amount")).intValue() : 0; + Integer mainTotalAmount = entry.get("main_total_amount") != null + ? ((Number) entry.get("main_total_amount")).intValue() + : 0; + Integer mainNetAmount = entry.get("main_net_amount") != null + ? ((Number) entry.get("main_net_amount")).intValue() + : 0; + Integer mainRefundedAmount = entry.get("main_refunded_amount") != null + ? ((Number) entry.get("main_refunded_amount")).intValue() + : 0; transformedData.get(category).put("main_total_amount", mainTotalAmount); transformedData.get(category).put("main_net_amount", mainNetAmount); transformedData.get(category).put("main_refunded_amount", mainRefundedAmount); } if (category.equals("past_future")) { - Integer pastbooking = entry.get("PAST_Events") != null ? ((Number) entry.get("PAST_Events")).intValue() : 0; - Integer futurebooking = entry.get("FUTURE_Events") != null ? ((Number) entry.get("FUTURE_Events")).intValue() : 0; + Integer pastbooking = entry.get("PAST_Events") != null ? ((Number) entry.get("PAST_Events")).intValue() + : 0; + Integer futurebooking = entry.get("FUTURE_Events") != null + ? ((Number) entry.get("FUTURE_Events")).intValue() + : 0; transformedData.get(category).put("PAST_Events", pastbooking); transformedData.get(category).put("FUTURE_Events", futurebooking); } @@ -2448,62 +2729,75 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { return bookingDetailsRepository.getHallDetailsForOfficer(hallIid); } - // @Override -// public List getAllPaymentsDetails(String fromDate, String toDate, String paymentStatus) { -// // TODO Auto-generated method stub -// return bookingDetailsRepository.getAllPaymentsDetails(fromDate, toDate,paymentStatus); -// } -// - //admin reports + // @Override + // public List getAllPaymentsDetails(String fromDate, String toDate, + // String paymentStatus) { + // // TODO Auto-generated method stub + // return bookingDetailsRepository.getAllPaymentsDetails(fromDate, + // toDate,paymentStatus); + // } + // + // admin reports @Override - public List getBookingDetailsByBookingDate(String fromDate, String toDate, String zone, String division, Integer hallid) { + public List getBookingDetailsByBookingDate(String fromDate, String toDate, String zone, String division, + Integer hallid) { // TODO Auto-generated method stub return bookingDetailsRepository.getBookingDetailsByBookingDate(fromDate, toDate, zone, division, hallid); } @Override - public List getBookingDetailsByEventDate(String fromDate, String toDate, String zone, String division, Integer hallid) { + public List getBookingDetailsByEventDate(String fromDate, String toDate, String zone, String division, + Integer hallid) { // TODO Auto-generated method stub return bookingDetailsRepository.getBookingDetailsByEventDate(fromDate, toDate, zone, division, hallid); } @Override public List getBookingDetailsByBookingDateWithStatus(String fromDate, String toDate, - String bookingStatus, String zone, String division, Integer hallid) { + String bookingStatus, String zone, String division, Integer hallid) { // TODO Auto-generated method stub - return bookingDetailsRepository.getBookingDetailsByBookingDateWithStatus(fromDate, toDate, bookingStatus, zone, division, hallid); + return bookingDetailsRepository.getBookingDetailsByBookingDateWithStatus(fromDate, toDate, bookingStatus, zone, + division, hallid); } @Override public List getBookingDetailsByEventDateWithStatus(String fromDate, String toDate, - String bookingStatus, String zone, String division, Integer hallid) { + String bookingStatus, String zone, String division, Integer hallid) { // TODO Auto-generated method stub - return bookingDetailsRepository.getBookingDetailsByEventDateWithStatus(fromDate, toDate, bookingStatus, zone, division, hallid); + return bookingDetailsRepository.getBookingDetailsByEventDateWithStatus(fromDate, toDate, bookingStatus, zone, + division, hallid); } @Override - public List getAllPaymentsDetails(String fromDate, String toDate, String paymentStatus, String zone, String division, Integer hallid) { + public List getAllPaymentsDetails(String fromDate, String toDate, String paymentStatus, String zone, + String division, Integer hallid) { // TODO Auto-generated method stub return bookingDetailsRepository.getAllPaymentsDetails(fromDate, toDate, paymentStatus, zone, division, hallid); } @Override - public List getAllExtraPaymentsDetails(String fromDate, String toDate, String paymentStatus, String zone, String division, Integer hallid) { + public List getAllExtraPaymentsDetails(String fromDate, String toDate, String paymentStatus, String zone, + String division, Integer hallid) { // TODO Auto-generated method stub - return bookingDetailsRepository.getAllExtraPaymentsDetails(fromDate, toDate, paymentStatus, zone, division, hallid); + return bookingDetailsRepository.getAllExtraPaymentsDetails(fromDate, toDate, paymentStatus, zone, division, + hallid); } @Override - public List getBookingHallDetailsReportByBookingDate(String fromDate, String toDate, String zone, String division, Integer hallid) { + public List getBookingHallDetailsReportByBookingDate(String fromDate, String toDate, String zone, + String division, Integer hallid) { // TODO Auto-generated method stub - return bookingDetailsRepository.getBookingHallDetailsReportByBookingDate(fromDate, toDate, zone, division, hallid); + return bookingDetailsRepository.getBookingHallDetailsReportByBookingDate(fromDate, toDate, zone, division, + hallid); } @Override - public List getBookingHallDetailsReportByEventDate(String fromDate, String toDate, String zone, String division, Integer hallid) { + public List getBookingHallDetailsReportByEventDate(String fromDate, String toDate, String zone, + String division, Integer hallid) { // TODO Auto-generated method stub - return bookingDetailsRepository.getBookingHallDetailsReportByEventDate(fromDate, toDate, zone, division, hallid); + return bookingDetailsRepository.getBookingHallDetailsReportByEventDate(fromDate, toDate, zone, division, + hallid); } @Override @@ -2514,9 +2808,10 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { @Override public List getAllBookingsettlementDetailsByBookingDateWithStatus(String fromDate, - String toDate, String refundStatus) { + String toDate, String refundStatus) { // TODO Auto-generated method stub - return bookingDetailsRepository.getAllBookingsettlementDetailsByBookingDateWithStatus(fromDate, toDate, refundStatus); + return bookingDetailsRepository.getAllBookingsettlementDetailsByBookingDateWithStatus(fromDate, toDate, + refundStatus); } @Override @@ -2527,97 +2822,104 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { @Override public List getAllBookingsettlementDetailsByEventDateWithStatus(String fromDate, - String toDate, String refundStatus) { + String toDate, String refundStatus) { // TODO Auto-generated method stub - return bookingDetailsRepository.getAllBookingsettlementDetailsByEventDateWithStatus(fromDate, toDate, refundStatus); + return bookingDetailsRepository.getAllBookingsettlementDetailsByEventDateWithStatus(fromDate, toDate, + refundStatus); } @Override public List getAllBookingDetailsBookingDateByZone(String fromDate, String toDate, - String zone) { + String zone) { // TODO Auto-generated method stub return bookingDetailsRepository.getAllBookingDetailsBookingDateByZone(fromDate, toDate, zone); } @Override public List getAllBookingDetailsEventDateByZone(String fromDate, String toDate, - String zone) { + String zone) { // TODO Auto-generated method stub return bookingDetailsRepository.getAllBookingDetailsEventDateByZone(fromDate, toDate, zone); } @Override public List getAllBookingDetailsBookingDateByZoneWithStatus(String fromDate, String toDate, - String zone, String bookingStatus) { + String zone, String bookingStatus) { // TODO Auto-generated method stub - return bookingDetailsRepository.getAllBookingDetailsBookingDateByZoneWithStatus(fromDate, toDate, zone, bookingStatus); + return bookingDetailsRepository.getAllBookingDetailsBookingDateByZoneWithStatus(fromDate, toDate, zone, + bookingStatus); } @Override public List getAllBookingDetailsEventDateByZoneWithStatus(String fromDate, String toDate, - String zone, String bookingStatus) { + String zone, String bookingStatus) { // TODO Auto-generated method stub - return bookingDetailsRepository.getAllBookingDetailsEventDateByZoneWithStatus(fromDate, toDate, zone, bookingStatus); + return bookingDetailsRepository.getAllBookingDetailsEventDateByZoneWithStatus(fromDate, toDate, zone, + bookingStatus); } @Override public List getAllBookingsettlementDetailsByZoneByBookingDate(String fromDate, - String toDate, String zone) { + String toDate, String zone) { // TODO Auto-generated method stub return bookingDetailsRepository.getAllBookingsettlementDetailsByZoneByBookingDate(fromDate, toDate, zone); } @Override public List getAllBookingsettlementDetailsByZoneByEventDate(String fromDate, String toDate, - String zone) { + String zone) { // TODO Auto-generated method stub return bookingDetailsRepository.getAllBookingsettlementDetailsByZoneByEventDate(fromDate, toDate, zone); } @Override public List getAllBookingsettlementDetailsByZoneByBookingDateWithStatus(String fromDate, - String toDate, String zone, String refundStatus) { + String toDate, String zone, String refundStatus) { // TODO Auto-generated method stub - return bookingDetailsRepository.getAllBookingsettlementDetailsByZoneByBookingDateWithStatus(fromDate, toDate, zone, refundStatus); + return bookingDetailsRepository.getAllBookingsettlementDetailsByZoneByBookingDateWithStatus(fromDate, toDate, + zone, refundStatus); } @Override public List getAllBookingsettlementDetailsByZoneByEventDateWithStatus(String fromDate, - String toDate, String zone, String refundStatus) { + String toDate, String zone, String refundStatus) { // TODO Auto-generated method stub - return bookingDetailsRepository.getAllBookingsettlementDetailsByZoneByEventDateWithStatus(fromDate, toDate, zone, refundStatus); + return bookingDetailsRepository.getAllBookingsettlementDetailsByZoneByEventDateWithStatus(fromDate, toDate, + zone, refundStatus); } @Override public List getBookingHallDetailsReportByZoneByBookingDate(String fromDate, String toDate, - String zone) { + String zone) { // TODO Auto-generated method stub return bookingDetailsRepository.getBookingHallDetailsReportByZoneByBookingDate(fromDate, toDate, zone); } @Override public List getBookingHallDetailsReportByZoneByEventDate(String fromDate, String toDate, - String zone) { + String zone) { // TODO Auto-generated method stub return bookingDetailsRepository.getBookingHallDetailsReportByZoneByEventDate(fromDate, toDate, zone); } @Override public List getBookingHallDetailsReportByZoneByBookingDateHallname(String fromDate, String toDate, - String zone, Integer hallId) { + String zone, Integer hallId) { // TODO Auto-generated method stub - return bookingDetailsRepository.getBookingHallDetailsReportByZoneByBookingDateHallname(fromDate, toDate, zone, hallId); + return bookingDetailsRepository.getBookingHallDetailsReportByZoneByBookingDateHallname(fromDate, toDate, zone, + hallId); } @Override public List getBookingHallDetailsReportByZoneByEventDateHallname(String fromDate, String toDate, - String zone, Integer hallId) { + String zone, Integer hallId) { // TODO Auto-generated method stub - return bookingDetailsRepository.getBookingHallDetailsReportByZoneByEventDateHallname(fromDate, toDate, zone, hallId); + return bookingDetailsRepository.getBookingHallDetailsReportByZoneByEventDateHallname(fromDate, toDate, zone, + hallId); } - //gccapps + // gccapps @Override public List getApprovedBookingDetails() { return bookingDetailsRepository.findByBookingStatus(BookingDetails.BookingStatus.APPROVED); @@ -2636,7 +2938,7 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { @Override public List getAllPaymentsDetails(String fromDate, String toDate) { // TODO Auto-generated method stub - //return bookingDetailsRepository.getAllPaymentsDetails(fromDate, toDate); + // return bookingDetailsRepository.getAllPaymentsDetails(fromDate, toDate); return null; } @@ -2645,13 +2947,11 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { return bookingDetailsRepository.findPastsEvents(); } - @Override public List getPresentsEvents() { return bookingDetailsRepository.findPresentsEvents(); } - @Override public List getFuturesEvents() { return bookingDetailsRepository.findFuturesEvents(); @@ -2665,7 +2965,7 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { @Override public List> getHallDetails(Integer hall_id) { // TODO Auto-generated method stub - //return bookingDetailsRepository.getHallDetails(hall_id); + // return bookingDetailsRepository.getHallDetails(hall_id); return null; } @@ -2673,7 +2973,7 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { return userRepository.findUserDetailsByBookingDate(fromDate, toDate); } - //developer + // developer @Override public List getTransactionresponse(String fromDate, String toDate, Long bookingId, Long hallId) { return transactionResponseRepository.getTransactionResponseByBookingId(fromDate, toDate, bookingId, hallId); @@ -2727,44 +3027,50 @@ public BookingDetails getBookingDetailsWithSettlement(int settlementId) { return bookingDetailsRepository.getCounterWiseBookingCount(fromDate, toDate); } - /*@Override - public List getHallWiseBookingDetails(String fromDate, String toDate) { - return bookingDetailsRepository.getHallWiseBookingDetails(fromDate, toDate); - } - - @Override - public List getBookingDetailsForAllHalls(String fromDate, String toDate){ - return bookingDetailsRepository.getBookingDetailsForAllHalls(fromDate,toDate); - }*/ + /* + * @Override + * public List getHallWiseBookingDetails(String fromDate, String + * toDate) { + * return bookingDetailsRepository.getHallWiseBookingDetails(fromDate, toDate); + * } + * + * @Override + * public List getBookingDetailsForAllHalls(String fromDate, String + * toDate){ + * return + * bookingDetailsRepository.getBookingDetailsForAllHalls(fromDate,toDate); + * } + */ @Override public List getHallWiseBookingDetails(String fromDate, String toDate, String counterId) { - return bookingDetailsRepository.getHallWiseBookingDetails(fromDate, toDate,counterId); + return bookingDetailsRepository.getHallWiseBookingDetails(fromDate, toDate, counterId); } @Override - public List getBookingDetailsForAllHalls(String fromDate, String toDate, String counterId,Integer hallid){ - return bookingDetailsRepository.getBookingDetailsForAllHalls(fromDate,toDate,counterId,hallid); + public List getBookingDetailsForAllHalls(String fromDate, String toDate, String counterId, + Integer hallid) { + return bookingDetailsRepository.getBookingDetailsForAllHalls(fromDate, toDate, counterId, hallid); } @Override - public List getCounterWiseBookingDetails(String fromDate, String toDate){ - return bookingDetailsRepository.getCounterWiseBookingDetails(fromDate,toDate); + public List getCounterWiseBookingDetails(String fromDate, String toDate) { + return bookingDetailsRepository.getCounterWiseBookingDetails(fromDate, toDate); } @Override - public List getZoneWiseBookingList(String fromDate, String toDate){ - return bookingDetailsRepository.getZoneWiseBookingList(fromDate,toDate); + public List getZoneWiseBookingList(String fromDate, String toDate) { + return bookingDetailsRepository.getZoneWiseBookingList(fromDate, toDate); } @Override - public List getAllHallWiseBookingList(String fromDate, String toDate){ - return bookingDetailsRepository.getHallWiseBookingList(fromDate,toDate); + public List getAllHallWiseBookingList(String fromDate, String toDate) { + return bookingDetailsRepository.getHallWiseBookingList(fromDate, toDate); } @Override - public List getAllCounterWiseBookingList(String fromDate, String toDate){ - return bookingDetailsRepository.getCounterWiseBookingList( fromDate,toDate); + public List getAllCounterWiseBookingList(String fromDate, String toDate) { + return bookingDetailsRepository.getCounterWiseBookingList(fromDate, toDate); } } diff --git a/src/main/java/com/gcc/communityHall/service/Impl/CounterServiceImpl.java b/src/main/java/com/gcc/communityHall/service/Impl/CounterServiceImpl.java index 61429118..e50faf4c 100644 --- a/src/main/java/com/gcc/communityHall/service/Impl/CounterServiceImpl.java +++ b/src/main/java/com/gcc/communityHall/service/Impl/CounterServiceImpl.java @@ -35,6 +35,7 @@ import com.gcc.communityHall.repository.BookingDocumentsRepository; import com.gcc.communityHall.repository.CounterDetailsRepository; import com.gcc.communityHall.repository.CounterRefundListRepository; import com.gcc.communityHall.repository.HallDetailsRepository; +import com.gcc.communityHall.repository.HallReasonRestrictionRepository; import com.gcc.communityHall.repository.HallImagesRepository; import com.gcc.communityHall.service.CounterService; import com.gcc.communityHall.service.DiscountRangeService; @@ -62,6 +63,8 @@ public class CounterServiceImpl implements CounterService { @Autowired private DiscountRangeService discountRangeService; + @Autowired + private HallReasonRestrictionRepository hallReasonRestrictionRepository; @Autowired private UserService userService; @@ -83,10 +86,10 @@ public class CounterServiceImpl implements CounterService { @Autowired CounterServiceImpl(CounterDetailsRepository counterRepo, - @Value("${file.dd.upload.directory}") String ddDirectory, - @Value("${file.dd.fullpath}") String ddPhotoUrl, - @Value("${file.counterrefund.upload.directory}") String refundDirectory, - @Value("${file.counterrefund.fullpath}") String refundPhotoUrl) { + @Value("${file.dd.upload.directory}") String ddDirectory, + @Value("${file.dd.fullpath}") String ddPhotoUrl, + @Value("${file.counterrefund.upload.directory}") String refundDirectory, + @Value("${file.counterrefund.fullpath}") String refundPhotoUrl) { this.counterRepo = counterRepo; this.ddDirectory = ddDirectory; this.ddPhotoUrl = ddPhotoUrl; @@ -95,7 +98,8 @@ public class CounterServiceImpl implements CounterService { } @Override - public CounterDetails saveCounterDetails(String bankName, int bankAccNo, int ddNumber, double amountReceived, MultipartFile counterddphoto, int bookingId) { + public CounterDetails saveCounterDetails(String bankName, int bankAccNo, int ddNumber, double amountReceived, + MultipartFile counterddphoto, int bookingId) { BookingDetails bookingDetails = bookingDetailsRepository.findById(bookingId) .orElseThrow(() -> new RuntimeException("Booking not found")); @@ -130,15 +134,26 @@ public class CounterServiceImpl implements CounterService { return counterdetails.orElse(null); } - @Override public Map saveCounterBooking(Map formData) { Map response = new HashMap<>(); BookingDetails bookingDetails = new BookingDetails(); - ReasonMaster reasonMaster = reasonMasterService.getReasonById(Integer.parseInt(formData.get("reasonId").toString())); + ReasonMaster reasonMaster = reasonMasterService + .getReasonById(Integer.parseInt(formData.get("reasonId").toString())); HallDetails hallDetails = hallDetailService.getHallById(Integer.parseInt(formData.get("hallId").toString())); Users user = userService.getUserById(userSession.getUserId()); + + // Validate reason restriction for this hall + if (hallDetails != null && hallDetails.isReasonRestricted()) { + java.util.List allowedReasonIds = hallReasonRestrictionRepository + .findReasonIdsByHallId(hallDetails.getHallId()); + if (!allowedReasonIds.isEmpty() && !allowedReasonIds.contains(reasonMaster.getReasonId())) { + response.put("status", "reason_restricted"); + return response; + } + } + String bookingId = formData.get("bookingId").toString(); if (bookingId != null && bookingId.equals("0")) { bookingDetails = new BookingDetails(); @@ -156,7 +171,7 @@ public class CounterServiceImpl implements CounterService { if (hallDetails != null) { bookingDetails.setHallDetails(hallDetails); -// bookingDetails.setDepositAmount(hallDetails.getDepositAmount()); + // bookingDetails.setDepositAmount(hallDetails.getDepositAmount()); String startDate = formData.get("startDate").toString(); String endDate = formData.get("endDate").toString(); String relation = formData.get("relation").toString(); @@ -170,23 +185,25 @@ public class CounterServiceImpl implements CounterService { double hallAmount = calcHallAmount(hallDetails, daysrange, startingSlot, endingSlot); double discountAmount = 0; String usertype = user.getUsertype().toString(); - if (usertype.equals("COUNCILLOR") || usertype.equals("PENSIONER") || usertype.equals("GCC_EMPLOYEE") || usertype.equals("PUBLIC")) { + if (usertype.equals("COUNCILLOR") || usertype.equals("PENSIONER") || usertype.equals("GCC_EMPLOYEE") + || usertype.equals("PUBLIC")) { discountAmount = (hallAmount * discount) / 100; } hallAmount = hallAmount - discountAmount; double gstAmount = (hallAmount * hallDetails.getGst()) / 100; - //double discountAmount=hallAmount*(1-(discount/100)); + // double discountAmount=hallAmount*(1-(discount/100)); double totalAmount = hallAmount + gstAmount + bookingDetails.getDepositAmount(); -// BigDecimal roundedTotalAmount = new BigDecimal(totalAmount).setScale(0, RoundingMode.HALF_UP); // Round to nearest whole number + // BigDecimal roundedTotalAmount = new BigDecimal(totalAmount).setScale(0, + // RoundingMode.HALF_UP); // Round to nearest whole number // Ensure two decimal places for display -// String formattedTotalAmount = String.format("%.2f", roundedTotalAmount.doubleValue()); + // String formattedTotalAmount = String.format("%.2f", + // roundedTotalAmount.doubleValue()); // Print the result -// System.out.println("Total Amount: " + formattedTotalAmount); - + // System.out.println("Total Amount: " + formattedTotalAmount); bookingDetails.setHallAmount(hallAmount); bookingDetails.setGst(gstAmount); @@ -201,7 +218,6 @@ public class CounterServiceImpl implements CounterService { bookingDetails.setRefundStatus(BookingDetails.RefundStatus.WAITING); bookingDetails.setBookingtype(BookingDetails.BookingType.OFFLINE); - bookingDetails = bookingDetailsRepository.save(bookingDetails); response.put("bookingId", bookingDetails.getBookingId()); @@ -215,7 +231,7 @@ public class CounterServiceImpl implements CounterService { response.put("gst", bookingDetails.getGst()); response.put("depositAmount", bookingDetails.getDepositAmount()); response.put("discount", discountrange.getDiscountRange()); - //response.put("totalAmount",formattedTotalAmount); + // response.put("totalAmount",formattedTotalAmount); response.put("username", bookingDetails.getUsers().getName()); response.put("userId", bookingDetails.getUsers().getUserId()); response.put("mobileNo", bookingDetails.getUsers().getMobileNo()); @@ -236,8 +252,10 @@ public class CounterServiceImpl implements CounterService { if (reasonDocMaster.isAddDocumentField()) { MultipartFile file = (MultipartFile) formData.get(reasonDocMaster.getDocFieldName()); String fileName = bookingDetails.getBookingId() + "_" + file.getOriginalFilename(); - String filePath = uploadDirectory + "/" + reasonMaster.getReason().toLowerCase() + "/" + fileName; - bookingDocument.setBookingDocUrl(serverPath + "images/" + reasonMaster.getReason().toLowerCase() + "/" + fileName); + String filePath = uploadDirectory + "/" + reasonMaster.getReason().toLowerCase() + "/" + + fileName; + bookingDocument.setBookingDocUrl( + serverPath + "images/" + reasonMaster.getReason().toLowerCase() + "/" + fileName); bookingDocument.setDocumentName(file.getOriginalFilename()); bookingDocument.setDocumentType(file.getContentType()); try (FileOutputStream fos = new FileOutputStream(filePath)) { @@ -258,10 +276,11 @@ public class CounterServiceImpl implements CounterService { private double calcHallAmount(HallDetails hallDetails, int days, int startingSlot, int endingSlot) { double hallAmount = 0; - if (days == 1 && startingSlot == 1 && endingSlot == 2) { //full day + if (days == 1 && startingSlot == 1 && endingSlot == 2) { // full day hallAmount = hallDetails.getFullDayRent(); - } else if (days == 1 && (startingSlot == 1 && endingSlot == 1) || (startingSlot == 2 && endingSlot == 2)) { // half day + } else if (days == 1 && (startingSlot == 1 && endingSlot == 1) || (startingSlot == 2 && endingSlot == 2)) { // half + // day hallAmount = hallDetails.getHalfDayRent(); } else if (days > 1) { if (startingSlot == 2 && endingSlot == 1) { @@ -288,13 +307,13 @@ public class CounterServiceImpl implements CounterService { return null; } - public CounterRefundList saveCancellation(int counterId, MultipartFile letterdocs, String reason) throws IOException { + public CounterRefundList saveCancellation(int counterId, MultipartFile letterdocs, String reason) + throws IOException { CounterRefundList counterRefundList = new CounterRefundList(); counterRefundList.setInitialisationStatus(CounterRefundList.InitialisationStatus.INITIATED); counterRefundList.setReasonforCancelling(reason); - if (letterdocs != null && !letterdocs.isEmpty()) { try { @@ -312,7 +331,6 @@ public class CounterServiceImpl implements CounterService { } } - CounterDetails counterDetails = new CounterDetails(); counterDetails.setCounterId(counterId); counterRefundList.setCounterDetails(counterDetails); diff --git a/src/main/resources/templates/admin/gccblocking.html b/src/main/resources/templates/admin/gccblocking.html index 8aa3c10f..987e84bd 100644 --- a/src/main/resources/templates/admin/gccblocking.html +++ b/src/main/resources/templates/admin/gccblocking.html @@ -110,50 +110,50 @@ -