From dd132f0fa88d56e8265d51f07b0cf0c2e3f36743 Mon Sep 17 00:00:00 2001 From: KaNi-04 <136799210+KaNi-04@users.noreply.github.com> Date: Tue, 9 Jun 2026 12:47:16 +0530 Subject: [PATCH] Reason master restriction and amount configuration changed --- .../controller/AdminAPIController.java | 682 ++++++-------- .../controller/OfficerAPIController.java | 882 +++++++++--------- .../entity/HallRequestDetails.java | 207 ++++ .../communityHall/entity/ReasonMaster.java | 47 +- .../PaymentRefundSlotOccupiedException.java | 11 +- .../controller/PaymentController.java | 780 +++++++++------- .../TransactionResponseRepository.java | 84 +- .../repository/BookingDetailsRepository.java | 39 + .../HallRequestDetailsRepository.java | 39 + .../repository/PaymentsRepository.java | 23 +- .../repository/ReasonMasterRepository.java | 5 +- .../communityHall/service/BookingService.java | 268 +++--- .../service/Impl/BookingServiceImpl.java | 380 +++++++- .../service/Impl/ReasonMasterImpl.java | 71 +- .../service/ReasonMasterService.java | 10 +- .../templates/user/hallbookingform.html | 4 +- 16 files changed, 2105 insertions(+), 1427 deletions(-) create mode 100644 src/main/java/com/gcc/communityHall/entity/HallRequestDetails.java create mode 100644 src/main/java/com/gcc/communityHall/repository/HallRequestDetailsRepository.java diff --git a/src/main/java/com/gcc/communityHall/controller/AdminAPIController.java b/src/main/java/com/gcc/communityHall/controller/AdminAPIController.java index ab9a87d..4ea7e8f 100644 --- a/src/main/java/com/gcc/communityHall/controller/AdminAPIController.java +++ b/src/main/java/com/gcc/communityHall/controller/AdminAPIController.java @@ -97,10 +97,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("/victoriahallbooking/admin/api") @AllArgsConstructor @@ -168,32 +165,10 @@ public class AdminAPIController { @Autowired private ApplicationLogsRepository applicationLogsRepository; - @Operation( - summary = "Update HallDetails REST API", - description = "REST API to update the Hall Details" - ) + @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 +245,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 +280,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 +296,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 +304,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 +358,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 +391,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 +448,61 @@ 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(); + // return reasonMasterService.getAllReasons(); + return reasonMasterService.getAllReasonsWithStatus(); } - @Operation( - summary = "Reason Documents by reasonId REST API", - description = "REST API to Get the ReasonDocuments By reasonId" - ) - //Getting ReasonDocuments By reasonId + @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 +510,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 +520,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 +546,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 +578,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 +623,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 +757,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 +778,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 +819,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 +889,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 +914,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 +941,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 +952,6 @@ public class AdminAPIController { } } - @GetMapping("/blockedHallsByHallIdAndReason") @ResponseBody public Map viewBlockedHallsByHallIdAndReason( @@ -1032,11 +960,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 +1013,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 +1021,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 +1030,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 +1041,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 +1066,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 +1092,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 +1155,7 @@ public class AdminAPIController { } } - //gccapps + // gccapps @GetMapping("/viewsettlement-pending") public ResponseEntity> viewSettlementPendingMaster(HttpSession session) { @@ -1239,7 +1171,6 @@ public class AdminAPIController { return ResponseEntity.ok(response); } - @GetMapping("/viewsettlement-complete") public ResponseEntity> viewSettlementcompleteMaster(HttpSession session) { @@ -1342,10 +1273,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 +1302,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 +1319,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 +1333,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 +1350,6 @@ public class AdminAPIController { return ResponseEntity.ok(halldetails); } - @GetMapping("/listgccblocking") public ResponseEntity> getGccBlocking() { @@ -1495,7 +1434,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 +1443,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/OfficerAPIController.java b/src/main/java/com/gcc/communityHall/controller/OfficerAPIController.java index 0ac93e7..4379a44 100644 --- a/src/main/java/com/gcc/communityHall/controller/OfficerAPIController.java +++ b/src/main/java/com/gcc/communityHall/controller/OfficerAPIController.java @@ -65,50 +65,46 @@ import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; import lombok.AllArgsConstructor; - -@Tag( - name = "CRUD REST APIs for Officer in CommunityHall", - description = "CRUD REST APIs in CommunityHall to CREATE, UPDATE, FETCH AND DELETE Booking details" -) +@Tag(name = "CRUD REST APIs for Officer in CommunityHall", description = "CRUD REST APIs in CommunityHall to CREATE, UPDATE, FETCH AND DELETE Booking details") @RestController @RequestMapping("/victoriahallbooking/api/officer") @AllArgsConstructor @Validated public class OfficerAPIController { - //ak// ak + // ak// ak @Autowired private SettlementHistoryRepository settlementHistoryRepository; - + @Autowired private UserService userService; - + @Autowired private SettlementService settlementService; - + @Autowired private BookingService bookingService; - + @Autowired private UserServiceImpl userServiceImpl; - + @Autowired private SettlementServiceImpl settlementServiceImpl; - + @Autowired private SettlementRepository settlementRepository; - + @Autowired private BookingServiceImpl bookingServiceImpl; - + @Autowired private UsersRepository usersRepository; - + @Autowired private BookingDetailsRepository bookingDetailsRepository; - + @Autowired private ReasonMasterService reasonMasterService; - + @Autowired private CounterRefundListRepository counterRefundListRepository; @Autowired @@ -121,95 +117,82 @@ public class OfficerAPIController { private PaymentsService paymentsService; @Autowired private BookingHistoryRepository bookingHistoryRepository; - + @Autowired private HttpSession session; - + @Autowired private ApplicationLogsRepository applicationLogsRepository; - - @Operation( - summary = "Retriving the User Details by userId REST API", - description = "REST API for Retriving the User Details by UserId" - ) - //Getting User Details by User Id + + @Operation(summary = "Retriving the User Details by userId REST API", description = "REST API for Retriving the User Details by UserId") + // Getting User Details by User Id @GetMapping("/getUserDetails") - public ResponseEntity getUsersByID(HttpServletRequest request, @RequestParam String usersid){ - Users user =userServiceImpl.getUserById(Integer.parseInt(usersid)); - return ResponseEntity.ok(user); - } - - @Operation( - summary = "Settlement List where the Refund Status is WAITING REST API", - description = "REST API for Retriving the Settlement List where the Refund Status is WAITING" - ) - //retrieving the Settlement List by Refund Status is WAITING - @GetMapping("/waiting-refund") - public List getSettlementsWithWaitingRefund() { - return settlementService.getSettlementListWithWaitingRefund(); - } - - @Operation( - summary = "Settlement List by Settlement Id REST API", - description = "REST API for Retriving the Settlement List by Settlement Id" - ) - //retrieving the Settlement List by Settlement Id + public ResponseEntity getUsersByID(HttpServletRequest request, @RequestParam String usersid) { + Users user = userServiceImpl.getUserById(Integer.parseInt(usersid)); + return ResponseEntity.ok(user); + } + + @Operation(summary = "Settlement List where the Refund Status is WAITING REST API", description = "REST API for Retriving the Settlement List where the Refund Status is WAITING") + // retrieving the Settlement List by Refund Status is WAITING + @GetMapping("/waiting-refund") + public List getSettlementsWithWaitingRefund() { + return settlementService.getSettlementListWithWaitingRefund(); + } + + @Operation(summary = "Settlement List by Settlement Id REST API", description = "REST API for Retriving the Settlement List by Settlement Id") + // retrieving the Settlement List by Settlement Id @GetMapping("/getSettlementList") - public ResponseEntity getBookingDetailsWithSettlement(HttpServletRequest request, @RequestParam String settlementsid) { - BookingDetails bookingDetails = bookingServiceImpl.getBookingDetailsWithSettlement(Integer.parseInt(settlementsid)); + public ResponseEntity getBookingDetailsWithSettlement(HttpServletRequest request, + @RequestParam String settlementsid) { + BookingDetails bookingDetails = bookingServiceImpl + .getBookingDetailsWithSettlement(Integer.parseInt(settlementsid)); System.out.println("bookingDetails:12 " + bookingDetails); - return ResponseEntity.ok(bookingDetails); + return ResponseEntity.ok(bookingDetails); } - + @GetMapping("/getsettlementListbyid") - public ResponseEntity> getsettlementlist(HttpServletRequest request, @RequestParam int settlementsid) { - Optional settlementlist=settlementRepository.findById(settlementsid); - return ResponseEntity.ok(settlementlist); + public ResponseEntity> getsettlementlist(HttpServletRequest request, + @RequestParam int settlementsid) { + Optional settlementlist = settlementRepository.findById(settlementsid); + return ResponseEntity.ok(settlementlist); } - - - @Operation( - summary = "Booking Details by Booking Id REST API", - description = "REST API for Retriving the Booking Details by Booking Id" - ) - //retrieving the Booking Details by Booking Id + + @Operation(summary = "Booking Details by Booking Id REST API", description = "REST API for Retriving the Booking Details by Booking Id") + // retrieving the Booking Details by Booking Id @GetMapping("/getBookingDetails") - public ResponseEntity getBookingsById(HttpServletRequest request, @RequestParam String bookingsId){ - BookingDetails book =bookingServiceImpl.getBookingsById(Integer.parseInt(bookingsId)); - return ResponseEntity.ok(book); - } - - @Operation( - summary = "Settlement APPROVED REST API", - description = "REST API for Updating the Refund Status to Approved by Settlement Id If the settlement is Approved" - ) - //Updating the Refund Status to Approved by Settlement Id If the settlement is Approved + public ResponseEntity getBookingsById(HttpServletRequest request, @RequestParam String bookingsId) { + BookingDetails book = bookingServiceImpl.getBookingsById(Integer.parseInt(bookingsId)); + return ResponseEntity.ok(book); + } + + @Operation(summary = "Settlement APPROVED REST API", description = "REST API for Updating the Refund Status to Approved by Settlement Id If the settlement is Approved") + // Updating the Refund Status to Approved by Settlement Id If the settlement is + // Approved @PostMapping("/updateApprovedSettlementStatus/{settlementId}") // need to check this API for settlement approval public ResponseEntity updateApprovedSettlementStatus( @PathVariable("settlementId") int settlementId, @RequestParam("status") BookingDetails.RefundStatus status, @RequestParam("comments") String comments) { - Map response = new HashMap<>(); - + Map response = new HashMap<>(); try { System.out.println("settlementId1: " + settlementId); - System.out.println("status"+status); - System.out.println("comments"+comments); - + System.out.println("status" + status); + System.out.println("comments" + comments); + // Update settlement status Settlement updateSettlement = settlementService.updateSettlementStatus(settlementId, status, comments); if (updateSettlement == null) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } - System.out.println("updateSettlement12"+updateSettlement); - //ak - // Set approvedFlag and approvedFlagDate - updateSettlement.setApprovedFlag(1); - updateSettlement.setApprovedFlagDate(new Date()); - settlementRepository.save(updateSettlement); - //ak - + System.out.println("updateSettlement12" + updateSettlement); + // ak + // Set approvedFlag and approvedFlagDate + updateSettlement.setApprovedFlag(1); + updateSettlement.setApprovedFlagDate(new Date()); + settlementRepository.save(updateSettlement); + // ak + // Log the action String adminname = (String) session.getAttribute("usertype"); Integer loginid = (Integer) session.getAttribute("id"); @@ -231,458 +214,439 @@ public class OfficerAPIController { applicationLogsRepository.save(logs); // Process refund request - String refundResponse = bookingServiceImpl.processRefundRequest(updateSettlement.getBookingDetails().getBookingId()); -//ak - // Prepare response map - - response.put("settlement", updateSettlement); - response.put("approvedFlag", updateSettlement.getApprovedFlag()); - response.put("approvedFlagDate", updateSettlement.getApprovedFlagDate()); + String refundResponse = bookingServiceImpl + .processRefundRequest(updateSettlement.getBookingDetails().getBookingId()); + // ak + // Prepare response map + + response.put("settlement", updateSettlement); + response.put("approvedFlag", updateSettlement.getApprovedFlag()); + response.put("approvedFlagDate", updateSettlement.getApprovedFlagDate()); if (refundResponse.contains("successful")) { // Refund success, return updated settlement and status - //return new ResponseEntity<>(updateSettlement, HttpStatus.OK); + // return new ResponseEntity<>(updateSettlement, HttpStatus.OK); return new ResponseEntity<>(response, HttpStatus.OK); } else { - + // Refund failure, update refund status to FAILURE - bookingService.updateRefundStatus(updateSettlement.getBookingDetails().getBookingId(), BookingDetails.RefundStatus.FAILURE); - Map responses = new HashMap<>(); - responses.put("approvedFlag", 1); - responses.put("message", "Refund processing failed: " + refundResponse); - responses.put("status", "FAILURE"); - - return new ResponseEntity<>(responses, HttpStatus.INTERNAL_SERVER_ERROR); - //return new ResponseEntity<>("Refund processing failed: " + refundResponse, HttpStatus.INTERNAL_SERVER_ERROR); + bookingService.updateRefundStatus(updateSettlement.getBookingDetails().getBookingId(), + BookingDetails.RefundStatus.FAILURE); + Map responses = new HashMap<>(); + responses.put("approvedFlag", 1); + responses.put("message", "Refund processing failed: " + refundResponse); + responses.put("status", "FAILURE"); + + return new ResponseEntity<>(responses, HttpStatus.INTERNAL_SERVER_ERROR); + // return new ResponseEntity<>("Refund processing failed: " + refundResponse, + // HttpStatus.INTERNAL_SERVER_ERROR); } } catch (Exception e) { - response.put("approvedFlag", 1); - response.put("message", "Exception while approving settlement: " + e.getMessage()); - return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); - - //return new ResponseEntity<>("An error occurred while processing the settlement for Settlement ID: " + settlementId, HttpStatus.INTERNAL_SERVER_ERROR); + response.put("approvedFlag", 1); + response.put("message", "Exception while approving settlement: " + e.getMessage()); + return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); + + // return new ResponseEntity<>("An error occurred while processing the + // settlement for Settlement ID: " + settlementId, + // HttpStatus.INTERNAL_SERVER_ERROR); } } - @Operation( - summary = "Settlement APPROVED REST API", - description = "REST API for Updating the Refund Status to Approved by Settlement Id If the settlement is Approved" - ) - //Updating the Refund Status to Rejected by Settlement Id If the settlement is Rejected + @Operation(summary = "Settlement APPROVED REST API", description = "REST API for Updating the Refund Status to Approved by Settlement Id If the settlement is Approved") + // Updating the Refund Status to Rejected by Settlement Id If the settlement is + // Rejected @PostMapping("/updateRejectSettlementStatus/{settlementId}") public ResponseEntity updateRejectSettlementStatus( @PathVariable("settlementId") int settlementId, @RequestParam("status") BookingDetails.RefundStatus status, - @RequestParam("comments") String comments){ - Settlement updateSettlement = settlementService.updateRejectSettlementStatus(settlementId, status, comments); - String adminname = (String) session.getAttribute("usertype"); - Integer loginid = (Integer) session.getAttribute("id"); - ApplicationLogs logs=new ApplicationLogs(); - logs.setComments("Action by " + adminname); - logs.setLoginId(loginid); - logs.setBookingId(updateSettlement.getBookingDetails().getBookingId()); - logs.setLogType("Booking Status:-"+status.toString()); - InetAddress inetAddress; - try { - inetAddress = InetAddress.getLocalHost(); - String hostname = InetAddress.getLocalHost().getHostName(); - logs.setIpaddress(inetAddress.getHostAddress()); - logs.setSystemName(hostname); - } catch (UnknownHostException e) { - e.printStackTrace(); - } - applicationLogsRepository.save(logs); - if (updateSettlement != null) { - return new ResponseEntity<>(updateSettlement, HttpStatus.OK); - } else { - return new ResponseEntity<>(HttpStatus.NOT_FOUND); - } + @RequestParam("comments") String comments) { + Settlement updateSettlement = settlementService.updateRejectSettlementStatus(settlementId, status, comments); + String adminname = (String) session.getAttribute("usertype"); + Integer loginid = (Integer) session.getAttribute("id"); + ApplicationLogs logs = new ApplicationLogs(); + logs.setComments("Action by " + adminname); + logs.setLoginId(loginid); + logs.setBookingId(updateSettlement.getBookingDetails().getBookingId()); + logs.setLogType("Booking Status:-" + status.toString()); + InetAddress inetAddress; + try { + inetAddress = InetAddress.getLocalHost(); + String hostname = InetAddress.getLocalHost().getHostName(); + logs.setIpaddress(inetAddress.getHostAddress()); + logs.setSystemName(hostname); + } catch (UnknownHostException e) { + e.printStackTrace(); + } + applicationLogsRepository.save(logs); + if (updateSettlement != null) { + return new ResponseEntity<>(updateSettlement, HttpStatus.OK); + } else { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } } - - @Operation( - summary = "USER STATUS APPROVED REST API", - description = "REST API for Updating the user Status Approved" - ) - //Updating the user Status Approved + + @Operation(summary = "USER STATUS APPROVED REST API", description = "REST API for Updating the user Status Approved") + // Updating the user Status Approved @PostMapping("/updateApprovedStatus/{userId}") public ResponseEntity updateApprovedStatus( - @PathVariable("userId") int userId, - @RequestParam("status") Users.userStatus status, - @RequestParam("comments") String comments) { - - Users updatedUser = userService.updateUserStatus(userId, status, comments); - if (updatedUser != null) { - return new ResponseEntity<>(updatedUser, HttpStatus.OK); - } else { - return new ResponseEntity<>(HttpStatus.NOT_FOUND); - } + @PathVariable("userId") int userId, + @RequestParam("status") Users.userStatus status, + @RequestParam("comments") String comments) { + + Users updatedUser = userService.updateUserStatus(userId, status, comments); + if (updatedUser != null) { + return new ResponseEntity<>(updatedUser, HttpStatus.OK); + } else { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } } - - @Operation( - summary = "USER STATUS REJECTED REST API", - description = "REST API for Updating the user Status Rejected" - ) - //Updating the user Status Rejected + + @Operation(summary = "USER STATUS REJECTED REST API", description = "REST API for Updating the user Status Rejected") + // Updating the user Status Rejected @PostMapping("/updateRejectStatus/{userId}") public ResponseEntity updateRejectStatus( - @PathVariable("userId") int userId, - @RequestParam("status") Users.userStatus status, - @RequestParam("comments") String comments) { + @PathVariable("userId") int userId, + @RequestParam("status") Users.userStatus status, + @RequestParam("comments") String comments) { - Users updatedUser = userService.updateUserStatus(userId, status, comments); + Users updatedUser = userService.updateUserStatus(userId, status, comments); - if (updatedUser != null) { - return new ResponseEntity<>(updatedUser, HttpStatus.OK); - } else { - return new ResponseEntity<>(HttpStatus.NOT_FOUND); - } + if (updatedUser != null) { + return new ResponseEntity<>(updatedUser, HttpStatus.OK); + } else { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } } - - @Operation( - summary = "BOOKING STATUS APPROVED REST API", - description = "REST API for Updating the Booking Status Approved by Booking Id" - ) - //Updating the Booking Status Approved by Booking Id + + @Operation(summary = "BOOKING STATUS APPROVED REST API", description = "REST API for Updating the Booking Status Approved by Booking Id") + // Updating the Booking Status Approved by Booking Id @PostMapping("/updateBookingApproved/{bookingId}") public ResponseEntity updateBookingApproved( - @PathVariable("bookingId") int bookingId, - @RequestParam("status") BookingDetails.BookingStatus status, - @RequestParam("comments") String comments) { - - BookingDetails updatedBooking = bookingService.updateBookingStatus(bookingId, status, comments); - String adminname = (String) session.getAttribute("usertype"); - Integer loginid = (Integer) session.getAttribute("id"); - ApplicationLogs logs=new ApplicationLogs(); - logs.setComments("Action by " + adminname); - logs.setLoginId(loginid); - logs.setBookingId(bookingId); - logs.setLogType("Booking Status:-"+status.toString()); - InetAddress inetAddress; + @PathVariable("bookingId") int bookingId, + @RequestParam("status") BookingDetails.BookingStatus status, + @RequestParam("comments") String comments) { + + BookingDetails updatedBooking = bookingService.updateBookingStatus(bookingId, status, comments); + String adminname = (String) session.getAttribute("usertype"); + Integer loginid = (Integer) session.getAttribute("id"); + ApplicationLogs logs = new ApplicationLogs(); + logs.setComments("Action by " + adminname); + logs.setLoginId(loginid); + logs.setBookingId(bookingId); + logs.setLogType("Booking Status:-" + status.toString()); + InetAddress inetAddress; try { inetAddress = InetAddress.getLocalHost(); - String hostname = InetAddress.getLocalHost().getHostName(); - logs.setIpaddress(inetAddress.getHostAddress()); - logs.setSystemName(hostname); + String hostname = InetAddress.getLocalHost().getHostName(); + logs.setIpaddress(inetAddress.getHostAddress()); + logs.setSystemName(hostname); } catch (UnknownHostException e) { e.printStackTrace(); } applicationLogsRepository.save(logs); - if (updatedBooking != null) { - return new ResponseEntity<>(updatedBooking, HttpStatus.OK); - } else { - return new ResponseEntity<>(HttpStatus.NOT_FOUND); - } + if (updatedBooking != null) { + return new ResponseEntity<>(updatedBooking, HttpStatus.OK); + } else { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } } - //ak - + // ak @PostMapping("/toggleStatus") public ResponseEntity toggleUserStatus( - @RequestParam Integer userId, - @RequestParam boolean active - ) { - //System.out.println("userID: " + userId + ", active or deactivate: " + active); - try { - userService.toggleUserStatus(userId, active); - return ResponseEntity.ok("User status updated successfully"); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to update user status"); - } + @RequestParam Integer userId, + @RequestParam boolean active) { + // System.out.println("userID: " + userId + ", active or deactivate: " + + // active); + try { + userService.toggleUserStatus(userId, active); + return ResponseEntity.ok("User status updated successfully"); + } catch (Exception e) { + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to update user status"); + } } - - @Operation( - summary = "BOOKING STATUS REJECTED REST API", - description = "REST API for Updating the Booking Status Rejected by Booking Id" - ) - //Updating the Booking Status Rejected by Booking Id + @Operation(summary = "BOOKING STATUS REJECTED REST API", description = "REST API for Updating the Booking Status Rejected by Booking Id") + // Updating the Booking Status Rejected by Booking Id @PostMapping("/updateBookingReject/{bookingId}") public ResponseEntity updateBookingReject( - @PathVariable("bookingId") int bookingId, - @RequestParam("status") BookingDetails.BookingStatus status, - @RequestParam("comments") String comments, - @RequestParam("reasontype") int reasontype) { - - if (reasontype == 1) { - Optional book=bookingDetailsRepository.findById(bookingId); - BookingDetails result=book.get(); - result.setBookingStatus(BookingStatus.REJECTED); - result.setRefundStatus(RefundStatus.NA); - List bookingCalendarList = bookingCalendarRepository.getCancellingdata1(String.valueOf(result.getBookingId())); - - for (BookingCalendar calendar : bookingCalendarList) { - boolean isUpdated = false; - - if (String.valueOf(result.getBookingId()).equals(calendar.getBookingId_1())) { - calendar.setBookingId_1(null); - isUpdated = true; - } - if (String.valueOf(result.getBookingId()).equals(calendar.getBookingId_2())) { - calendar.setBookingId_2(null); - isUpdated = true; - } - if (calendar.isMorningSlot()) { - calendar.setMorningSlot(false); - isUpdated = true; - } - if (calendar.isEveningSlot()) { - calendar.setEveningSlot(false); - isUpdated = true; - } - if (isUpdated) { - calendar.setIs_delete(true); - bookingCalendarRepository.save(calendar); - } - } - bookingDetailsRepository.save(result); - String adminname = (String) session.getAttribute("usertype"); - Integer loginid = (Integer) session.getAttribute("id"); - ApplicationLogs logs=new ApplicationLogs(); - logs.setComments("Action by " + adminname); - logs.setLoginId(loginid); - logs.setBookingId(bookingId); - logs.setLogType("Booking Status:-"+status.toString()); - InetAddress inetAddress; + @PathVariable("bookingId") int bookingId, + @RequestParam("status") BookingDetails.BookingStatus status, + @RequestParam("comments") String comments, + @RequestParam("reasontype") int reasontype) { + + if (reasontype == 1) { + Optional book = bookingDetailsRepository.findById(bookingId); + BookingDetails result = book.get(); + result.setBookingStatus(BookingStatus.REJECTED); + result.setRefundStatus(RefundStatus.NA); + List bookingCalendarList = bookingCalendarRepository + .getCancellingdata1(String.valueOf(result.getBookingId())); + + for (BookingCalendar calendar : bookingCalendarList) { + boolean isUpdated = false; + + if (String.valueOf(result.getBookingId()).equals(calendar.getBookingId_1())) { + calendar.setBookingId_1(null); + isUpdated = true; + } + if (String.valueOf(result.getBookingId()).equals(calendar.getBookingId_2())) { + calendar.setBookingId_2(null); + isUpdated = true; + } + if (calendar.isMorningSlot()) { + calendar.setMorningSlot(false); + isUpdated = true; + } + if (calendar.isEveningSlot()) { + calendar.setEveningSlot(false); + isUpdated = true; + } + if (isUpdated) { + calendar.setIs_delete(true); + bookingCalendarRepository.save(calendar); + } + } + bookingDetailsRepository.save(result); + String adminname = (String) session.getAttribute("usertype"); + Integer loginid = (Integer) session.getAttribute("id"); + ApplicationLogs logs = new ApplicationLogs(); + logs.setComments("Action by " + adminname); + logs.setLoginId(loginid); + logs.setBookingId(bookingId); + logs.setLogType("Booking Status:-" + status.toString()); + InetAddress inetAddress; try { inetAddress = InetAddress.getLocalHost(); - String hostname = InetAddress.getLocalHost().getHostName(); - logs.setIpaddress(inetAddress.getHostAddress()); - logs.setSystemName(hostname); + String hostname = InetAddress.getLocalHost().getHostName(); + logs.setIpaddress(inetAddress.getHostAddress()); + logs.setSystemName(hostname); } catch (UnknownHostException e) { e.printStackTrace(); } - return ResponseEntity.ok(result); - } else if (reasontype == 2) { - BookingDetails rejectBooking = bookingService.updateCancelledBookingStatus(bookingId, status, comments); - Optional book=bookingDetailsRepository.findById(bookingId); - BookingDetails bookingDetails=book.get(); - String rejectionsms="Your booking ID "+bookingDetails.getBookingId()+" on "+bookingDetails.getStartDate()+" has been rejected by GCC due to insufficient details."; - String rejectedurlString ="https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to="+bookingDetails.getUsers().getMobileNo()+"&from=GCCCRP&body="+rejectionsms+"&entityid=1401572690000011081&templateid=1407172346485956648"; - //String rejectedwhatsupmsg="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+rejected+by+GCC+due+to+insufficient+details.+%0AThanks+for+using+GCC+Community+Hall+Booking+System."; - String rejectedwhatsupmsg="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+rejected+by+GCC+due+to+insufficient+details."; + return ResponseEntity.ok(result); + } else if (reasontype == 2) { + BookingDetails rejectBooking = bookingService.updateCancelledBookingStatus(bookingId, status, comments); + Optional book = bookingDetailsRepository.findById(bookingId); + BookingDetails bookingDetails = book.get(); + String rejectionsms = "Your booking ID " + bookingDetails.getBookingId() + " on " + + bookingDetails.getStartDate() + " has been rejected by GCC due to insufficient details."; + String rejectedurlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + + bookingDetails.getUsers().getMobileNo() + "&from=GCCCRP&body=" + rejectionsms + + "&entityid=1401572690000011081&templateid=1407172346485956648"; + // String + // rejectedwhatsupmsg="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+rejected+by+GCC+due+to+insufficient+details.+%0AThanks+for+using+GCC+Community+Hall+Booking+System."; + String rejectedwhatsupmsg = "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+rejected+by+GCC+due+to+insufficient+details."; whatsappMsgServiceImpl.sendMsg(rejectedwhatsupmsg); - whatsappMsgServiceImpl.sendSMS(rejectedurlString); - String adminname = (String) session.getAttribute("usertype"); - Integer loginid = (Integer) session.getAttribute("id"); - ApplicationLogs logs=new ApplicationLogs(); - logs.setComments("Action by " + adminname); - logs.setLoginId(loginid); - logs.setBookingId(bookingId); - logs.setLogType("Booking Status:-"+status.toString()); - InetAddress inetAddress; + whatsappMsgServiceImpl.sendSMS(rejectedurlString); + String adminname = (String) session.getAttribute("usertype"); + Integer loginid = (Integer) session.getAttribute("id"); + ApplicationLogs logs = new ApplicationLogs(); + logs.setComments("Action by " + adminname); + logs.setLoginId(loginid); + logs.setBookingId(bookingId); + logs.setLogType("Booking Status:-" + status.toString()); + InetAddress inetAddress; try { inetAddress = InetAddress.getLocalHost(); - String hostname = InetAddress.getLocalHost().getHostName(); - logs.setIpaddress(inetAddress.getHostAddress()); - logs.setSystemName(hostname); + String hostname = InetAddress.getLocalHost().getHostName(); + logs.setIpaddress(inetAddress.getHostAddress()); + logs.setSystemName(hostname); } catch (UnknownHostException e) { e.printStackTrace(); } - applicationLogsRepository.save(logs); - return ResponseEntity.ok(rejectBooking); - } else { - return ResponseEntity.badRequest().body("Invalid reasontype"); - } + applicationLogsRepository.save(logs); + return ResponseEntity.ok(rejectBooking); + } else { + return ResponseEntity.badRequest().body("Invalid reasontype"); + } } - - @Operation( - summary = "Retrieving BOOKING STATUS APPROVED REST API", - description = "REST API for retrieving the Booking Status Approved" - ) - //retrieving the Booking Status Approved + + @Operation(summary = "Retrieving BOOKING STATUS APPROVED REST API", description = "REST API for retrieving the Booking Status Approved") + // retrieving the Booking Status Approved @GetMapping("/user-Approved") public ResponseEntity> getUserApprovedList() { - List userApproved = usersRepository.getUserApproved(); - return new ResponseEntity<>(userApproved, HttpStatus.OK); - } - - @Operation( - summary = "Retrieving BOOKING STATUS REJECTED REST API", - description = "REST API for retrieving the Booking Status Rejected" - ) - //retrieving the Booking Status Rejected + List userApproved = usersRepository.getUserApproved(); + return new ResponseEntity<>(userApproved, HttpStatus.OK); + } + + @Operation(summary = "Retrieving BOOKING STATUS REJECTED REST API", description = "REST API for retrieving the Booking Status Rejected") + // retrieving the Booking Status Rejected @GetMapping("/user-Reject") public ResponseEntity> getUserRejectedList() { - List userReject = usersRepository.getUserReject(); - return new ResponseEntity<>(userReject, HttpStatus.OK); - } - - - @Operation( - summary = "Counter Refund Approval by Officer REST API", - description = "REST API to approve the Counter Refund by Officer" - ) - //RefundApproval by Officer - @PostMapping("/approveRefund/{id}") - public ResponseEntity approveRefund(@PathVariable int id) { - Optional refundListOptional = counterRefundListRepository.findById(id); - - if (refundListOptional.isPresent()) { - CounterRefundList refundList = refundListOptional.get(); - refundList.setInitialisationStatus(CounterRefundList.InitialisationStatus.APPROVED); - counterRefundListRepository.save(refundList); - return new ResponseEntity<>("Refund with counterId " + id + " has been approved", HttpStatus.OK); - } else { - return new ResponseEntity<>("Refund with counterId " + id + " not found", HttpStatus.NOT_FOUND); - } + List userReject = usersRepository.getUserReject(); + return new ResponseEntity<>(userReject, HttpStatus.OK); + } + + @Operation(summary = "Counter Refund Approval by Officer REST API", description = "REST API to approve the Counter Refund by Officer") + // RefundApproval by Officer + @PostMapping("/approveRefund/{id}") + public ResponseEntity approveRefund(@PathVariable int id) { + Optional refundListOptional = counterRefundListRepository.findById(id); + + if (refundListOptional.isPresent()) { + CounterRefundList refundList = refundListOptional.get(); + refundList.setInitialisationStatus(CounterRefundList.InitialisationStatus.APPROVED); + counterRefundListRepository.save(refundList); + return new ResponseEntity<>("Refund with counterId " + id + " has been approved", HttpStatus.OK); + } else { + return new ResponseEntity<>("Refund with counterId " + id + " not found", HttpStatus.NOT_FOUND); } - - @Operation( - summary = "Counter Refund Reject by Officer REST API", - description = "REST API to Reject the Counter Refund by Officer" - ) - //RefundReject by Officer - @PostMapping("/rejectRefund/{id}") - public ResponseEntity rejectRefund(@PathVariable int id) { - Optional rejectRefund = counterRefundListRepository.findById(id); - - if (rejectRefund.isPresent()) { - CounterRefundList refundList = rejectRefund.get(); - refundList.setInitialisationStatus(CounterRefundList.InitialisationStatus.REJECTED); - counterRefundListRepository.save(refundList); - return new ResponseEntity<>("Refund with counterId " + id + " has been approved", HttpStatus.OK); - } else { - return new ResponseEntity<>("Refund with counterId " + id + " not found", HttpStatus.NOT_FOUND); - } + } + + @Operation(summary = "Counter Refund Reject by Officer REST API", description = "REST API to Reject the Counter Refund by Officer") + // RefundReject by Officer + @PostMapping("/rejectRefund/{id}") + public ResponseEntity rejectRefund(@PathVariable int id) { + Optional rejectRefund = counterRefundListRepository.findById(id); + + if (rejectRefund.isPresent()) { + CounterRefundList refundList = rejectRefund.get(); + refundList.setInitialisationStatus(CounterRefundList.InitialisationStatus.REJECTED); + counterRefundListRepository.save(refundList); + return new ResponseEntity<>("Refund with counterId " + id + " has been approved", HttpStatus.OK); + } else { + return new ResponseEntity<>("Refund with counterId " + id + " not found", HttpStatus.NOT_FOUND); } - - @Operation( - summary = "Reason By reasonName REST API", - description = "REST API to get the Reason Details with the reason" - ) - //retrieving the Reason Details with the reason - @GetMapping("/getReasonByName") - public ResponseEntity getReasonByName(@RequestParam String reasonName){ - return ResponseEntity.ok(reasonMasterService.getReasonByName(reasonName)); - } - + } + + @Operation(summary = "Reason By reasonName REST API", description = "REST API to get the Reason Details with the reason") + // retrieving the Reason Details with the reason + @GetMapping("/getReasonByName") + public ResponseEntity getReasonByName(@RequestParam String reasonName) { + return ResponseEntity.ok(reasonMasterService.getReasonByName(reasonName)); + } + @PostMapping("/uploadChallonDetails/{settlementId}") public ResponseEntity updateApprovedSettlementStatus( - @PathVariable("settlementId") int settlementId, - @RequestParam(name = "ddNumber", required = false) Long ddNumber, - @RequestParam(name = "ddDate", required = false) String ddDate, - @RequestParam(name = "ddamount", required = false) Long ddamount, - @RequestParam(name = "challonnumber", required = false) Long challonnumber, - @RequestParam(name = "challonamount", required = false) Long challonamount, - @RequestParam(name = "challonimage") MultipartFile challonimage) { - - // Add null checks and default values if necessary - Settlement settlement = settlementService.uploadChallonDetails( - settlementId, - ddNumber != null ? ddNumber : 0L, - ddDate, - ddamount != null ? ddamount : 0L, - challonimage, - challonnumber != null ? challonnumber : 0L, - challonamount != null ? challonamount : 0L); - - if (settlement != null) { - return new ResponseEntity<>(settlement, HttpStatus.OK); - } else { - return new ResponseEntity<>(HttpStatus.NOT_FOUND); - } + @PathVariable("settlementId") int settlementId, + @RequestParam(name = "ddNumber", required = false) Long ddNumber, + @RequestParam(name = "ddDate", required = false) String ddDate, + @RequestParam(name = "ddamount", required = false) Long ddamount, + @RequestParam(name = "challonnumber", required = false) Long challonnumber, + @RequestParam(name = "challonamount", required = false) Long challonamount, + @RequestParam(name = "challonimage") MultipartFile challonimage) { + + // Add null checks and default values if necessary + Settlement settlement = settlementService.uploadChallonDetails( + settlementId, + ddNumber != null ? ddNumber : 0L, + ddDate, + ddamount != null ? ddamount : 0L, + challonimage, + challonnumber != null ? challonnumber : 0L, + challonamount != null ? challonamount : 0L); + + if (settlement != null) { + return new ResponseEntity<>(settlement, HttpStatus.OK); + } else { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } } @PostMapping("/approveCancelledBookingRefund/{bookingId}") public ResponseEntity updateCancelledRefundStatus( - @PathVariable("bookingId") int bookingId, - @RequestParam("status") BookingDetails.RefundStatus status) { - try { - // Update refund status preliminarily -// //BookingDetails updatedBooking = bookingService.updateRefundStatus(bookingId, status); -// if (updatedBooking == null) { -// return new ResponseEntity<>("Booking not found for ID: " + bookingId, HttpStatus.NOT_FOUND); -// } - - // Log the action - String adminName = (String) session.getAttribute("usertype"); - Integer loginId = (Integer) session.getAttribute("id"); - ApplicationLogs logs = new ApplicationLogs(); - logs.setComments("Action by " + adminName); - logs.setLoginId(loginId); - logs.setBookingId(bookingId); - logs.setLogType("Settlement Approve: " + status.toString()); - - try { - InetAddress inetAddress = InetAddress.getLocalHost(); - String hostname = InetAddress.getLocalHost().getHostName(); - logs.setIpaddress(inetAddress.getHostAddress()); - logs.setSystemName(hostname); - } catch (UnknownHostException e) { - e.printStackTrace(); - } - - applicationLogsRepository.save(logs); - - // Process refund and adjust refund status accordingly - String refundResponse = bookingServiceImpl.processRefundRequest(bookingId); - - if (refundResponse.contains("successful")) { - // Refund success: leave refund status as updated - return new ResponseEntity<>(refundResponse, HttpStatus.OK); - } else { - // Refund failure: update refund status to FAILURE - bookingService.updateRefundStatus(bookingId, BookingDetails.RefundStatus.FAILURE); - return new ResponseEntity<>(refundResponse, HttpStatus.INTERNAL_SERVER_ERROR); - } - - } catch (Exception e) { - return new ResponseEntity<>("An error occurred while processing the refund for Booking ID: " + bookingId, HttpStatus.INTERNAL_SERVER_ERROR); - } - } + @PathVariable("bookingId") int bookingId, + @RequestParam("status") BookingDetails.RefundStatus status) { + try { + // Update refund status preliminarily + // //BookingDetails updatedBooking = + // bookingService.updateRefundStatus(bookingId, status); + // if (updatedBooking == null) { + // return new ResponseEntity<>("Booking not found for ID: " + bookingId, + // HttpStatus.NOT_FOUND); + // } + + // Log the action + String adminName = (String) session.getAttribute("usertype"); + Integer loginId = (Integer) session.getAttribute("id"); + ApplicationLogs logs = new ApplicationLogs(); + logs.setComments("Action by " + adminName); + logs.setLoginId(loginId); + logs.setBookingId(bookingId); + logs.setLogType("Settlement Approve: " + status.toString()); + + try { + InetAddress inetAddress = InetAddress.getLocalHost(); + String hostname = InetAddress.getLocalHost().getHostName(); + logs.setIpaddress(inetAddress.getHostAddress()); + logs.setSystemName(hostname); + } catch (UnknownHostException e) { + e.printStackTrace(); + } + + applicationLogsRepository.save(logs); + + // Process refund and adjust refund status accordingly + String refundResponse = bookingServiceImpl.processRefundRequest(bookingId); + + if (refundResponse.contains("successful")) { + // Refund success: leave refund status as updated + return new ResponseEntity<>(refundResponse, HttpStatus.OK); + } else { + // Refund failure: update refund status to FAILURE + bookingService.updateRefundStatus(bookingId, BookingDetails.RefundStatus.FAILURE); + return new ResponseEntity<>(refundResponse, HttpStatus.INTERNAL_SERVER_ERROR); + } + } catch (Exception e) { + return new ResponseEntity<>("An error occurred while processing the refund for Booking ID: " + bookingId, + HttpStatus.INTERNAL_SERVER_ERROR); + } + } @GetMapping("/bookingstatistics") - public ResponseEntity>> getBookingStatistics( - @RequestParam (required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate fromDate, - @RequestParam (required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate toDate, - HttpSession session, - @RequestParam(required = false) String division, - @RequestParam(required=false, defaultValue = "1000") Integer hallid, - @RequestParam(required = false) String userType) { - - - + public ResponseEntity>> getBookingStatistics( + @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate fromDate, + @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate toDate, + HttpSession session, + @RequestParam(required = false) String division, + @RequestParam(required = false, defaultValue = "1000") Integer hallid, + @RequestParam(required = false) String userType) { + String zone = (String) session.getAttribute("zone"); - Map> statistics = bookingService.getOfficerDashboard(fromDate, toDate, zone, division, hallid, userType); - return ResponseEntity.ok(statistics); - + Map> statistics = bookingService.getOfficerDashboard(fromDate, toDate, zone, + division, hallid, userType); + return ResponseEntity.ok(statistics); + } - + @GetMapping("/getHallsDetailsByZone") - public ResponseEntity> getHallsDetailsByZone(@RequestParam String zone) - { - - - Map hallzones=hallDetailService.getHallsDetailsForOfficer(zone); - return ResponseEntity.ok(hallzones); - } - + public ResponseEntity> getHallsDetailsByZone(@RequestParam String zone) { + + Map hallzones = hallDetailService.getHallsDetailsForOfficer(zone); + return ResponseEntity.ok(hallzones); + } + @GetMapping("/byhallid") - public ResponseEntity>> getBookingDetailsByHallId(@RequestParam int hallId) { - List> bookingDetails = bookingService.getHallDetailsForOfficer(hallId); - return ResponseEntity.ok(bookingDetails); - } - - //gccapps + public ResponseEntity>> getBookingDetailsByHallId(@RequestParam int hallId) { + List> bookingDetails = bookingService.getHallDetailsForOfficer(hallId); + return ResponseEntity.ok(bookingDetails); + } + + // gccapps @GetMapping("/getApprovedBookingDetails") - public List getApprovedBookingDetails() { - return bookingService.getApprovedBookingDetails(); - } - + public List getApprovedBookingDetails() { + return bookingService.getApprovedBookingDetails(); + } + @GetMapping("/getRejectedBookingDetails") - public List getRejectedBookingDetails() { - return bookingService.getRejectedBookingDetails(); - } + public List getRejectedBookingDetails() { + return bookingService.getRejectedBookingDetails(); + } + @GetMapping("/getwaitingforNOCapproval") - public List getWaitingforNOCapproval() { - return bookingService.getWaitingforNOCapproval(); - } - + public List getWaitingforNOCapproval() { + return bookingService.getWaitingforNOCapproval(); + } + @GetMapping("/getAllPaymentList") - public List getAllPaymentList() { - return paymentsService.getAllPaymentDetails(); - } + public List getAllPaymentList() { + return paymentsService.getAllPaymentDetails(); + } } diff --git a/src/main/java/com/gcc/communityHall/entity/HallRequestDetails.java b/src/main/java/com/gcc/communityHall/entity/HallRequestDetails.java new file mode 100644 index 0000000..5f36cce --- /dev/null +++ b/src/main/java/com/gcc/communityHall/entity/HallRequestDetails.java @@ -0,0 +1,207 @@ +package com.gcc.communityHall.entity; + +import jakarta.persistence.*; +import java.time.LocalDateTime; + +@Entity +@Table(name = "hall_request_details") +public class HallRequestDetails { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "req_id") + private Integer reqId; + + @Column(name = "booking_id") + private Integer bookingId; + + @Column(name = "start_date") + private String startDate; + + @Column(name = "end_date") + private String endDate; + + @Column(name = "starting_slot") + private Integer startingSlot; + + @Column(name = "ending_slot") + private Integer endingSlot; + + @Column(name = "reason") + private String reason; + + @Column(name = "booking_status") + private String bookingStatus; + + @Column(name = "hall_id") + private Integer hallId; + + @Column(name = "user_id") + private Integer userId; + + @Column(name = "org_type", length = 15) + private String orgType; + + @Column(name = "event_description") + private String eventDescription; + + @Column(name = "office_details") + private String officeDetails; + + @Column(name = "bonafide_path") + private String bonafidePath; + + @Column(name = "cdate", insertable = false, updatable = false) + private LocalDateTime cdate; + + @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) + private BookingDetails bookingDetails; + + // @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) + // private Users users; + + // @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) + // private HallDetails hallDetails; + + // Getters and Setters + + public Integer getReqId() { + return reqId; + } + + public void setReqId(Integer reqId) { + this.reqId = reqId; + } + + public String getStartDate() { + return startDate; + } + + public void setStartDate(String startDate) { + this.startDate = startDate; + } + + public String getEndDate() { + return endDate; + } + + public void setEndDate(String endDate) { + this.endDate = endDate; + } + + public Integer getStartingSlot() { + return startingSlot; + } + + public void setStartingSlot(Integer startingSlot) { + this.startingSlot = startingSlot; + } + + public Integer getEndingSlot() { + return endingSlot; + } + + public void setEndingSlot(Integer endingSlot) { + this.endingSlot = endingSlot; + } + + public String getReason() { + return reason; + } + + public void setReason(String reason) { + this.reason = reason; + } + + public String getBookingStatus() { + return bookingStatus; + } + + public void setBookingStatus(String bookingStatus) { + this.bookingStatus = bookingStatus; + } + + public Integer getHallId() { + return hallId; + } + + public void setHallId(Integer hallId) { + this.hallId = hallId; + } + + public Integer getUserId() { + return userId; + } + + public void setUserId(Integer userId) { + this.userId = userId; + } + + public String getOrgType() { + return orgType; + } + + public void setOrgType(String orgType) { + this.orgType = orgType; + } + + public String getEventDescription() { + return eventDescription; + } + + public void setEventDescription(String eventDescription) { + this.eventDescription = eventDescription; + } + + public String getOfficeDetails() { + return officeDetails; + } + + public void setOfficeDetails(String officeDetails) { + this.officeDetails = officeDetails; + } + + public String getBonafidePath() { + return bonafidePath; + } + + public void setBonafidePath(String bonafidePath) { + this.bonafidePath = bonafidePath; + } + + public LocalDateTime getCdate() { + return cdate; + } + + // public Users getUsers() { + // return users; + // } + + // public void setUsers(Users users) { + // this.users = users; + // } + + // public HallDetails getHallDetails() { + // return hallDetails; + // } + + // public void setHallDetails(HallDetails hallDetails) { + // this.hallDetails = hallDetails; + // } + + public Integer getBookingId() { + return bookingId; + } + + public void setBookingId(Integer bookingId) { + this.bookingId = bookingId; + } + + public BookingDetails getBookingDetails() { + return bookingDetails; + } + + public void setBookingDetails(BookingDetails bookingDetails) { + this.bookingDetails = bookingDetails; + } +} diff --git a/src/main/java/com/gcc/communityHall/entity/ReasonMaster.java b/src/main/java/com/gcc/communityHall/entity/ReasonMaster.java index 737102c..969004b 100644 --- a/src/main/java/com/gcc/communityHall/entity/ReasonMaster.java +++ b/src/main/java/com/gcc/communityHall/entity/ReasonMaster.java @@ -23,7 +23,10 @@ public class ReasonMaster { private String updatedBy; private int maxdays; - @OneToMany(mappedBy = "reasonMaster",fetch = FetchType.LAZY,cascade = CascadeType.ALL) + private boolean isActive; + private boolean isDelete; + + @OneToMany(mappedBy = "reasonMaster", fetch = FetchType.LAZY, cascade = CascadeType.ALL) private List reasonDocumentMasterList; public int getReasonId() { @@ -66,20 +69,36 @@ public class ReasonMaster { this.reasonDocumentMasterList = reasonDocumentMasterList; } - public int getMaxdays() { - return maxdays; - } + public int getMaxdays() { + return maxdays; + } + + public void setMaxdays(int maxdays) { + this.maxdays = maxdays; + } + + public String getReasoncode() { + return reasoncode; + } + + public void setReasoncode(String reasoncode) { + this.reasoncode = reasoncode; + } + + public void setActive(boolean isActive) { + this.isActive = isActive; + } - public void setMaxdays(int maxdays) { - this.maxdays = maxdays; - } + public boolean getActive() { + return isActive; + } - public String getReasoncode() { - return reasoncode; - } + public void setDelete(boolean isDelete) { + this.isDelete = isDelete; + } + + public boolean getDelete() { + return isDelete; + } - public void setReasoncode(String reasoncode) { - this.reasoncode = reasoncode; - } - } diff --git a/src/main/java/com/gcc/communityHall/exception/PaymentRefundSlotOccupiedException.java b/src/main/java/com/gcc/communityHall/exception/PaymentRefundSlotOccupiedException.java index 7d76bdc..f911710 100644 --- a/src/main/java/com/gcc/communityHall/exception/PaymentRefundSlotOccupiedException.java +++ b/src/main/java/com/gcc/communityHall/exception/PaymentRefundSlotOccupiedException.java @@ -9,15 +9,14 @@ import com.gcc.communityHall.service.Impl.BookingServiceImpl; import com.gcc.communityHall.service.WhatsappMsgService; import org.springframework.beans.factory.annotation.Autowired; -public class PaymentRefundSlotOccupiedException extends RuntimeException{ +public class PaymentRefundSlotOccupiedException extends RuntimeException { + // @Autowired + // BookingService bookingService; -// @Autowired -// BookingService bookingService; + private String exMsg; - private String exMsg; - - public PaymentRefundSlotOccupiedException(String exMsg){ + public PaymentRefundSlotOccupiedException(String exMsg) { super(exMsg); } } diff --git a/src/main/java/com/gcc/communityHall/paymentService/controller/PaymentController.java b/src/main/java/com/gcc/communityHall/paymentService/controller/PaymentController.java index 9a905e0..db774f2 100644 --- a/src/main/java/com/gcc/communityHall/paymentService/controller/PaymentController.java +++ b/src/main/java/com/gcc/communityHall/paymentService/controller/PaymentController.java @@ -41,11 +41,10 @@ import com.gcc.communityHall.service.UserService; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; - @Controller @RequestMapping("/victoriahallbooking/payment") public class PaymentController { - //ak + // ak @Autowired private EncryptionUtil encryptionUtil; @@ -73,143 +72,32 @@ public class PaymentController { @Autowired private AppConfig appConfig; -// @Autowired -// private ErpPostDataRepository erpPostDataRepository; + // @Autowired + // private ErpPostDataRepository erpPostDataRepository; @Autowired private PaymentsService paymentsService; -//ak -@PostMapping(value = "/response") -public String response(Model model, @RequestParam(required = false) String msg) throws NoSuchAlgorithmException { - - String salt = this.paymentConfig.getEncryptionKey(); - String confirmToken = ""; - String status = this.paymentConfig.getTransactionSuccessCode(); - - String[] res = msg.split("\\|"); - String c = ""; - - TransactionResponse response = this.paymentService.getTransactionResponseByTxansactionId(res[3], "temp"); - - Payments payment = new Payments(); - payment.setTransactionId(response.getTxansactionId()); - double amount = 0; - - // ------------------ PAYMENT STRING PROCESSING ------------------ - for (int i = 0; i < res.length; i++) { - - if (i == res.length - 1) { - c = c + salt; - confirmToken = res[i]; - } else if (res[i].isEmpty()) { - c = c + "|"; - } else if (res[i].equals("NA")) { - c = c + "NA|"; - } else { - c = c + res[i] + "|"; - } - - if (i == 5) { - response.setTpslTxnId(res[i]); - response.setAmount(res[6]); - response.setTxansactionId(res[3]); - response.setDate(res[8]); - } - } - - int bookingId = response.getBookingId(); - - try { - amount = Double.parseDouble(response.getAmount()); - } catch (Exception e) {} - - payment.setAmountReceived(amount); - payment.setPaymentStatus("Not Completed"); - - BookingDetails bookingsDetails = bookser.getBookingsById(bookingId); // JPA fetch - payment.setBookingDetails(bookingsDetails); - response.setResponse(msg); - response.setStatusCode(res[0]); - bookingsDetails.setPayments(payment); - payment.setCdate(new Date()); - - // save transaction response - transactionResRepo.save(response); - - // ============================================================= - // CASE 1: FAILURE - AMOUNT MISMATCH - // ============================================================= - if (bookingsDetails.getAmountReceived() != amount) { - - if(paymentService.generateToken(c).equals(confirmToken) && status.equals(res[0])){ - payment.setPaymentStatus("Success"); - bookingsDetails.setPayments(payment); - paymentRepo.save(payment); - - // booking failure logic - bookser.bookingFailure(bookingsDetails, 1); - } - - // Fetch OR Generate booking_ref_id - String refId = bookser.getBookingRefIdByBookingId(bookingId); - - // encrypt bookingId (coworkspace logic) - String encryptedId = encryptionUtil.encrypt(String.valueOf(bookingId)); - - model.addAttribute("ref_id", refId); - model.addAttribute("encryptedId", encryptedId); - - return "redirect:/victoriahallbooking/user/acknowledgement?ref_id=" + refId; - } - - // ============================================================= - // CASE 2: SUCCESS FLOW - // ============================================================= - if (paymentService.generateToken(c).equals(confirmToken) && status.equals(res[0])) { - - payment.setPaymentStatus("Success"); - bookingsDetails.setPayments(payment); - paymentRepo.save(payment); - - try { - bookser.confirmBooking(bookingId); - } catch (Exception e) { - // ignore - } - } - - // 🔥 Fetch OR Generate booking_ref_id - String refId = bookser.getBookingRefIdByBookingId(bookingId); - - // 🔐 Encrypt bookingId - String encryptedId = encryptionUtil.encrypt(String.valueOf(bookingId)); - - model.addAttribute("ref_id", refId); - model.addAttribute("encryptedId", encryptedId); - - return "redirect:/victoriahallbooking/user/acknowledgement?ref_id=" + refId; -} - - - /* @PostMapping(value = "/response") + // ak + @PostMapping(value = "/response") public String response(Model model, @RequestParam(required = false) String msg) throws NoSuchAlgorithmException { String salt = this.paymentConfig.getEncryptionKey(); - String confirmToken = ""; String status = this.paymentConfig.getTransactionSuccessCode(); - String s = new String(msg); - String c = new String(); - String res[] = s.split("\\|"); + + String[] res = msg.split("\\|"); + String c = ""; TransactionResponse response = this.paymentService.getTransactionResponseByTxansactionId(res[3], "temp"); + Payments payment = new Payments(); payment.setTransactionId(response.getTxansactionId()); double amount = 0; - + // ------------------ PAYMENT STRING PROCESSING ------------------ for (int i = 0; i < res.length; i++) { + if (i == res.length - 1) { c = c + salt; confirmToken = res[i]; @@ -225,178 +113,331 @@ public String response(Model model, @RequestParam(required = false) String msg) response.setTpslTxnId(res[i]); response.setAmount(res[6]); response.setTxansactionId(res[3]); - //String[] tDate = res[8].split(" "); response.setDate(res[8]); } } + int bookingId = response.getBookingId(); + try { amount = Double.parseDouble(response.getAmount()); } catch (Exception e) { - // TODO: handle exception - //System.out.println("payment Controller lineNo-67"); } + payment.setAmountReceived(amount); payment.setPaymentStatus("Not Completed"); - BookingDetails bookingsDetails = bookser.getBookingsById(bookingId); + BookingDetails bookingsDetails = bookser.getBookingsById(bookingId); // JPA fetch payment.setBookingDetails(bookingsDetails); response.setResponse(msg); response.setStatusCode(res[0]); bookingsDetails.setPayments(payment); payment.setCdate(new Date()); - System.out.println("bookingsDetails.getAmountReceived().." + bookingsDetails.getAmountReceived()); - System.out.println("amount: " + amount); + // save transaction response + transactionResRepo.save(response); - TransactionResponse save = transactionResRepo.save(response); + // ============================================================= + // CASE 1: FAILURE - AMOUNT MISMATCH + // ============================================================= + if (bookingsDetails.getAmountReceived() != amount) { - if (bookingsDetails.getAmountReceived() != amount) { // Reject booking if the amount is incorrect - if(paymentService.generateToken(c).equals(confirmToken) && status.equals(res[0])){ + if (paymentService.generateToken(c).equals(confirmToken) && status.equals(res[0])) { payment.setPaymentStatus("Success"); bookingsDetails.setPayments(payment); paymentRepo.save(payment); + + // booking failure logic bookser.bookingFailure(bookingsDetails, 1); } - //ak - + // Fetch OR Generate booking_ref_id + String refId = bookser.getBookingRefIdByBookingId(bookingId); - model.addAttribute("bookingsDetails", bookingsDetails); - return "redirect:/victoriahallbooking/user/acknowledgement?bookingId=" + bookingsDetails.getBookingId(); - } + // encrypt bookingId (coworkspace logic) + String encryptedId = encryptionUtil.encrypt(String.valueOf(bookingId)); + model.addAttribute("ref_id", refId); + model.addAttribute("encryptedId", encryptedId); + return "redirect:/victoriahallbooking/user/acknowledgement?ref_id=" + refId; + } + + // ============================================================= + // CASE 2: SUCCESS FLOW + // ============================================================= if (paymentService.generateToken(c).equals(confirmToken) && status.equals(res[0])) { + payment.setPaymentStatus("Success"); bookingsDetails.setPayments(payment); - try { - String confirmBooking = bookser.confirmBooking(response.getBookingId()); - }catch (Exception e){ -// return "redirect:/communityhall/user/acknowledgement?bookingId=" + bookingsDetails.getBookingId(); + paymentRepo.save(payment); + try { + bookser.confirmBooking(bookingId); + } catch (Exception e) { + // ignore } -// postDataToERP(payment, response); // post payment details to ERP -// System.out.println("\n confirmBooking:- paymentController 111"+confirmBooking+"\n"); -// if(confirmBooking.equals("Booking confirmed successfully")) { -// //bookser.updateBookingStatusById(bookingsDetails.getBookingId(), BookingDetails.BookingStatus.APPROVED, "confirm"); -// // String bookingconfimationsms = "Your booking with ID "+bookingsDetails.getBookingId()+" on" +bookingsDetails.getBookingId()+" has been successfully confirmed. Thanks for using GCC Community Hall Booking System."; -// }else if(confirmBooking.equals("Slot occupied")) { -//// System.out.println("Slot occupied line 115"); -//// BookingDetails crrSts = bookser.updateBookingStatusById(bookingsDetails.getBookingId(), BookingDetails.BookingStatus.REFUNDED, "slot occupied Refund will happen shortly"); -//// System.out.println("BookingDetails:-"+crrSts.getBookingStatus()); -// } -// else if(confirmBooking.equals("Error confirming booking")) { -// bookser.updateBookingStatusById(bookingsDetails.getBookingId(), BookingDetails.BookingStatus.PENDING, "Error"); -// -// } - } - // System.out.println(response.toString()); - model.addAttribute("bookingsDetails", bookingsDetails); // Add single BookingDetails object - //System.out.println(save.toString()); - paymentRepo.save(payment); - return "redirect:/victoriahallbooking/user/acknowledgement?bookingId=" + bookingsDetails.getBookingId(); - }*/ - - /*public void postDataToERP(Payments payment, TransactionResponse res) { - RestTemplate restTemplate = new RestTemplate(); - erpPostData erpData = new erpPostData(); - - SimpleDateFormat outputFormat = new SimpleDateFormat("dd/MM/yyyy"); - String txDate = outputFormat.format(payment.getCdate()); - String assesNo = LocalDate.now().getYear() + "/COMM/" + res.getBookingId(); - - Map data = new TreeMap<>(); - *//*static mandatory input to be sent *//* - data.put("serviceId", "getOtherCollection"); - data.put("COLLECTION_TYPE", "Community Hall"); - data.put("TOTALTRANSACTIONCODE", "450310000"); -// /end of static/ -// /unique data to be send/ - data.put("ASSESSMENTNO", assesNo); - data.put("UNIQUERECEIPTID", res.getBookingId()); - data.put("TRANSACTIONNO", payment.getTransactionId()); - data.put("TRANSACTIONREFNO", res.getTpslTxnId()); - data.put("TRANSACTIONDATE", txDate); //payment date format dd/mm/yyyy -> 19/02/2025 - data.put("TOTALTRANSACTIONAMOUNT", payment.getBookingDetails().getAmountReceived()); - - data.put("MSTRCODEONE", "061"); - data.put("SPLITAMOUNTONE", payment.getBookingDetails().getHallAmount()); - data.put("MSTRCODETWO", "062"); - data.put("SPLITAMOUNTTWO", payment.getBookingDetails().getDepositAmount()); - data.put("MSTRCODETHREE", "063"); - data.put("SPLITAMOUNTTHREE", payment.getBookingDetails().getGst()); -// /Amount Collected from party/ - data.put("PARTYNAME", payment.getBookingDetails().getUsers().getName()); - data.put("PARTYADDRESS", payment.getBookingDetails().getUsers().getStreet() + "," + - payment.getBookingDetails().getUsers().getArea() + "," + payment.getBookingDetails().getUsers().getLocation() + "," + - payment.getBookingDetails().getUsers().getPinCode()); - data.put("PARTYMOBILE", payment.getBookingDetails().getUsers().getMobileNo()); - *//* end *//* - System.out.println(data); - System.out.println(appConfig.getCommErpUrl()); -// ResponseEntity stringResponseEntity = restTemplate.postForEntity(appConfig.getErpUrl(), data, String.class); -// System.out.println(stringResponseEntity.getBody()); - - erpData.setTx_id(payment.getTransactionId()); - erpData.setBooking_det_booking_id(res.getBookingId()); - erpData.setStatus(true); - erpData.setCdate(LocalDate.now()); - erpData.setPay_status(1); - erpPostDataRepository.save(erpData); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(appConfig.getCommErpUrl()); - for (Map.Entry entry : data.entrySet()) { - builder.queryParam(entry.getKey(), entry.getValue()); - } - - String urlMsg = builder.toUriString(); - System.out.println(urlMsg); - - try { - HttpURLConnection connection = null; - - URL url = new URL(urlMsg); - connection = (HttpURLConnection) url.openConnection(); - connection.setRequestMethod("GET"); - - int responseCode = connection.getResponseCode(); -// response=responseCode+""; - System.out.println("Response Code: " + responseCode); - - if (responseCode == HttpURLConnection.HTTP_OK) { // 200 OK - BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); - String inputLine; - StringBuilder response = new StringBuilder(); - while ((inputLine = in.readLine()) != null) { - response.append(inputLine); - } - in.close(); - System.out.println("Response: " + response.toString()); - - ObjectMapper objectMapper = new ObjectMapper(); - JsonNode jsonNode = objectMapper.readTree(response.toString()); + // 🔥 Fetch OR Generate booking_ref_id + String refId = bookser.getBookingRefIdByBookingId(bookingId); - String resultStatus = jsonNode.get("ResultStatus").asText(); + // 🔐 Encrypt bookingId + String encryptedId = encryptionUtil.encrypt(String.valueOf(bookingId)); - if (!resultStatus.isEmpty() && resultStatus.equals("false")) { - erpData.setStatus(false); - erpPostDataRepository.save(erpData); - } + model.addAttribute("ref_id", refId); + model.addAttribute("encryptedId", encryptedId); - } else { - System.out.println("GET request failed."); - } + return "redirect:/victoriahallbooking/user/acknowledgement?ref_id=" + refId; + } - } catch (Exception e) { - e.printStackTrace(); - } - }*/ + /* + * @PostMapping(value = "/response") + * public String response(Model model, @RequestParam(required = false) String + * msg) throws NoSuchAlgorithmException { + * + * String salt = this.paymentConfig.getEncryptionKey(); + * + * String confirmToken = ""; + * String status = this.paymentConfig.getTransactionSuccessCode(); + * String s = new String(msg); + * String c = new String(); + * String res[] = s.split("\\|"); + * + * TransactionResponse response = + * this.paymentService.getTransactionResponseByTxansactionId(res[3], "temp"); + * Payments payment = new Payments(); + * payment.setTransactionId(response.getTxansactionId()); + * double amount = 0; + * + * + * for (int i = 0; i < res.length; i++) { + * if (i == res.length - 1) { + * c = c + salt; + * confirmToken = res[i]; + * } else if (res[i].isEmpty()) { + * c = c + "|"; + * } else if (res[i].equals("NA")) { + * c = c + "NA|"; + * } else { + * c = c + res[i] + "|"; + * } + * + * if (i == 5) { + * response.setTpslTxnId(res[i]); + * response.setAmount(res[6]); + * response.setTxansactionId(res[3]); + * //String[] tDate = res[8].split(" "); + * response.setDate(res[8]); + * } + * } + * int bookingId = response.getBookingId(); + * try { + * amount = Double.parseDouble(response.getAmount()); + * } catch (Exception e) { + * // TODO: handle exception + * //System.out.println("payment Controller lineNo-67"); + * } + * payment.setAmountReceived(amount); + * payment.setPaymentStatus("Not Completed"); + * + * BookingDetails bookingsDetails = bookser.getBookingsById(bookingId); + * payment.setBookingDetails(bookingsDetails); + * response.setResponse(msg); + * response.setStatusCode(res[0]); + * bookingsDetails.setPayments(payment); + * payment.setCdate(new Date()); + * + * System.out.println("bookingsDetails.getAmountReceived().." + + * bookingsDetails.getAmountReceived()); + * System.out.println("amount: " + amount); + * + * TransactionResponse save = transactionResRepo.save(response); + * + * if (bookingsDetails.getAmountReceived() != amount) { // Reject booking if the + * amount is incorrect + * if(paymentService.generateToken(c).equals(confirmToken) && + * status.equals(res[0])){ + * payment.setPaymentStatus("Success"); + * bookingsDetails.setPayments(payment); + * paymentRepo.save(payment); + * bookser.bookingFailure(bookingsDetails, 1); + * } + * //ak + * + * + * + * model.addAttribute("bookingsDetails", bookingsDetails); + * return "redirect:/victoriahallbooking/user/acknowledgement?bookingId=" + + * bookingsDetails.getBookingId(); + * } + * + * + * if (paymentService.generateToken(c).equals(confirmToken) && + * status.equals(res[0])) { + * payment.setPaymentStatus("Success"); + * bookingsDetails.setPayments(payment); + * try { + * String confirmBooking = bookser.confirmBooking(response.getBookingId()); + * }catch (Exception e){ + * // return "redirect:/communityhall/user/acknowledgement?bookingId=" + + * bookingsDetails.getBookingId(); + * + * } + * // postDataToERP(payment, response); // post payment details to ERP + * // + * System.out.println("\n confirmBooking:- paymentController 111"+confirmBooking + * +"\n"); + * // if(confirmBooking.equals("Booking confirmed successfully")) { + * // //bookser.updateBookingStatusById(bookingsDetails.getBookingId(), + * BookingDetails.BookingStatus.APPROVED, "confirm"); + * // // String bookingconfimationsms = + * "Your booking with ID "+bookingsDetails.getBookingId()+" on" + * +bookingsDetails.getBookingId() + * +" has been successfully confirmed. Thanks for using GCC Community Hall Booking System." + * ; + * // }else if(confirmBooking.equals("Slot occupied")) { + * //// System.out.println("Slot occupied line 115"); + * //// BookingDetails crrSts = + * bookser.updateBookingStatusById(bookingsDetails.getBookingId(), + * BookingDetails.BookingStatus.REFUNDED, + * "slot occupied Refund will happen shortly"); + * //// System.out.println("BookingDetails:-"+crrSts.getBookingStatus()); + * // } + * // else if(confirmBooking.equals("Error confirming booking")) { + * // bookser.updateBookingStatusById(bookingsDetails.getBookingId(), + * BookingDetails.BookingStatus.PENDING, "Error"); + * // + * // } + * + * } + * + * // System.out.println(response.toString()); + * model.addAttribute("bookingsDetails", bookingsDetails); // Add single + * BookingDetails object + * //System.out.println(save.toString()); + * paymentRepo.save(payment); + * return "redirect:/victoriahallbooking/user/acknowledgement?bookingId=" + + * bookingsDetails.getBookingId(); + * } + */ + + /* + * public void postDataToERP(Payments payment, TransactionResponse res) { + * RestTemplate restTemplate = new RestTemplate(); + * erpPostData erpData = new erpPostData(); + * + * SimpleDateFormat outputFormat = new SimpleDateFormat("dd/MM/yyyy"); + * String txDate = outputFormat.format(payment.getCdate()); + * String assesNo = LocalDate.now().getYear() + "/COMM/" + res.getBookingId(); + * + * Map data = new TreeMap<>(); + *//* static mandatory input to be sent *//* + * data.put("serviceId", "getOtherCollection"); + * data.put("COLLECTION_TYPE", "Community Hall"); + * data.put("TOTALTRANSACTIONCODE", "450310000"); + * // /end of static/ + * // /unique data to be send/ + * data.put("ASSESSMENTNO", assesNo); + * data.put("UNIQUERECEIPTID", res.getBookingId()); + * data.put("TRANSACTIONNO", payment.getTransactionId()); + * data.put("TRANSACTIONREFNO", res.getTpslTxnId()); + * data.put("TRANSACTIONDATE", txDate); //payment date format dd/mm/yyyy + * -> 19/02/2025 + * data.put("TOTALTRANSACTIONAMOUNT", + * payment.getBookingDetails().getAmountReceived()); + * + * data.put("MSTRCODEONE", "061"); + * data.put("SPLITAMOUNTONE", + * payment.getBookingDetails().getHallAmount()); + * data.put("MSTRCODETWO", "062"); + * data.put("SPLITAMOUNTTWO", + * payment.getBookingDetails().getDepositAmount()); + * data.put("MSTRCODETHREE", "063"); + * data.put("SPLITAMOUNTTHREE", payment.getBookingDetails().getGst()); + * // /Amount Collected from party/ + * data.put("PARTYNAME", + * payment.getBookingDetails().getUsers().getName()); + * data.put("PARTYADDRESS", + * payment.getBookingDetails().getUsers().getStreet() + "," + + * payment.getBookingDetails().getUsers().getArea() + "," + + * payment.getBookingDetails().getUsers().getLocation() + "," + + * payment.getBookingDetails().getUsers().getPinCode()); + * data.put("PARTYMOBILE", + * payment.getBookingDetails().getUsers().getMobileNo()); + *//* end *//* + * System.out.println(data); + * System.out.println(appConfig.getCommErpUrl()); + * // ResponseEntity stringResponseEntity = + * restTemplate.postForEntity(appConfig.getErpUrl(), data, + * String.class); + * // System.out.println(stringResponseEntity.getBody()); + * + * erpData.setTx_id(payment.getTransactionId()); + * erpData.setBooking_det_booking_id(res.getBookingId()); + * erpData.setStatus(true); + * erpData.setCdate(LocalDate.now()); + * erpData.setPay_status(1); + * erpPostDataRepository.save(erpData); + * + * UriComponentsBuilder builder = + * UriComponentsBuilder.fromHttpUrl(appConfig.getCommErpUrl()) + * ; + * for (Map.Entry entry : data.entrySet()) { + * builder.queryParam(entry.getKey(), entry.getValue()); + * } + * + * String urlMsg = builder.toUriString(); + * System.out.println(urlMsg); + * + * try { + * HttpURLConnection connection = null; + * + * URL url = new URL(urlMsg); + * connection = (HttpURLConnection) url.openConnection(); + * connection.setRequestMethod("GET"); + * + * int responseCode = connection.getResponseCode(); + * // response=responseCode+""; + * System.out.println("Response Code: " + responseCode); + * + * if (responseCode == HttpURLConnection.HTTP_OK) { // 200 OK + * BufferedReader in = new BufferedReader(new + * InputStreamReader(connection.getInputStream())); + * String inputLine; + * StringBuilder response = new StringBuilder(); + * while ((inputLine = in.readLine()) != null) { + * response.append(inputLine); + * } + * in.close(); + * System.out.println("Response: " + response.toString()); + * + * ObjectMapper objectMapper = new ObjectMapper(); + * JsonNode jsonNode = + * objectMapper.readTree(response.toString()); + * + * String resultStatus = + * jsonNode.get("ResultStatus").asText(); + * + * if (!resultStatus.isEmpty() && + * resultStatus.equals("false")) { + * erpData.setStatus(false); + * erpPostDataRepository.save(erpData); + * } + * + * } else { + * System.out.println("GET request failed."); + * } + * + * } catch (Exception e) { + * e.printStackTrace(); + * } + * } + */ @PostMapping(value = "/additionaldamage-response") - public String additionaldamagePaymentresponse(Model model, @RequestParam(required = false) String msg) throws NoSuchAlgorithmException { + public String additionaldamagePaymentresponse(Model model, @RequestParam(required = false) String msg) + throws NoSuchAlgorithmException { String salt = this.paymentConfig.getEncryptionKey(); @@ -411,7 +452,6 @@ public String response(Model model, @RequestParam(required = false) String msg) payment.setTransactionId(response.getTxansactionId()); double amount = 0; - for (int i = 0; i < res.length; i++) { if (i == res.length - 1) { c = c + salt; @@ -428,7 +468,7 @@ public String response(Model model, @RequestParam(required = false) String msg) response.setTpslTxnId(res[i]); response.setAmount(res[6]); response.setTxansactionId(res[3]); - //String[] tDate = res[8].split(" "); + // String[] tDate = res[8].split(" "); response.setDate(res[8]); } } @@ -437,7 +477,7 @@ public String response(Model model, @RequestParam(required = false) String msg) amount = Double.parseDouble(response.getAmount()); } catch (Exception e) { // TODO: handle exception - //System.out.println("payment Controller lineNo-67"); + // System.out.println("payment Controller lineNo-67"); } payment.setAmountReceived(amount); payment.setPaymentStatus("Not Completed"); @@ -462,108 +502,128 @@ public String response(Model model, @RequestParam(required = false) String msg) } model.addAttribute("bookingsDetails", bookingsDetails); extraPaymentsRepository.save(payment); -// postEPDataToERP(payment, response); //post extra payments details to ERP - // return "redirect:/communityhall/user/collectionpendingacknowledgement?bookingId=" + bookingsDetails.getBookingId(); - return "redirect:/victoriahallbooking/user/collectionpendingacknowledgement?bookingId=" + bookingsDetails.getBookingId(); + // postEPDataToERP(payment, response); //post extra payments details to ERP + // return + // "redirect:/communityhall/user/collectionpendingacknowledgement?bookingId=" + + // bookingsDetails.getBookingId(); + return "redirect:/victoriahallbooking/user/collectionpendingacknowledgement?bookingId=" + + bookingsDetails.getBookingId(); } - /*public void postEPDataToERP(ExtraPayments payment, TransactionResponse res) { - RestTemplate restTemplate = new RestTemplate(); - erpPostData erpData = new erpPostData(); - - SimpleDateFormat outputFormat = new SimpleDateFormat("dd/MM/yyyy"); - String txDate = outputFormat.format(payment.getCdate()); - String assesNo = LocalDate.now().getYear() + "/COMM/ED/" + res.getBookingId(); - - Map data = new TreeMap<>(); - *//*static mandatory input to be sent *//* - data.put("serviceId", "getOtherCollection"); - data.put("COLLECTION_TYPE", "Community Hall"); - data.put("TOTALTRANSACTIONCODE", "450310000"); -// /end of static/ -// /unique data to be send/ - data.put("ASSESSMENTNO", assesNo); - data.put("UNIQUERECEIPTID", res.getBookingId()); - data.put("TRANSACTIONNO", payment.getTransactionId()); - data.put("TRANSACTIONREFNO", res.getTpslTxnId()); - data.put("TRANSACTIONDATE", txDate); //payment date format dd/mm/yyyy -> 19/02/2025 - data.put("TOTALTRANSACTIONAMOUNT", payment.getAmountReceived()); - - data.put("MSTRCODEONE", "061"); - data.put("SPLITAMOUNTONE", 0); - data.put("MSTRCODETWO", "062"); - data.put("SPLITAMOUNTTWO", payment.getAmountReceived()); - data.put("MSTRCODETHREE", "063"); - data.put("SPLITAMOUNTTHREE", 0); -// /Amount Collected from party/ - data.put("PARTYNAME", payment.getBookingDetails().getUsers().getName()); - data.put("PARTYADDRESS", payment.getBookingDetails().getUsers().getStreet() + "," + - payment.getBookingDetails().getUsers().getArea() + "," + payment.getBookingDetails().getUsers().getLocation() + "," + - payment.getBookingDetails().getUsers().getPinCode()); - data.put("PARTYMOBILE", payment.getBookingDetails().getUsers().getMobileNo()); - *//* end *//* - System.out.println(data); - System.out.println(appConfig.getCommErpUrl()); -// ResponseEntity stringResponseEntity = restTemplate.postForEntity(appConfig.getErpUrl(), data, String.class); -// System.out.println(stringResponseEntity.getBody()); - - erpData.setTx_id(payment.getTransactionId()); - erpData.setBooking_det_booking_id(res.getBookingId()); - erpData.setStatus(true); - erpData.setCdate(LocalDate.now()); - erpData.setPay_status(2); - erpPostDataRepository.save(erpData); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(appConfig.getCommErpUrl()); - for (Map.Entry entry : data.entrySet()) { - builder.queryParam(entry.getKey(), entry.getValue()); - } - - String urlMsg = builder.toUriString(); - System.out.println(urlMsg); - - try { - HttpURLConnection connection = null; - - URL url = new URL(urlMsg); - connection = (HttpURLConnection) url.openConnection(); - connection.setRequestMethod("GET"); - - int responseCode = connection.getResponseCode(); -// response=responseCode+""; - System.out.println("Response Code: " + responseCode); - - if (responseCode == HttpURLConnection.HTTP_OK) { // 200 OK - BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); - String inputLine; - StringBuilder response = new StringBuilder(); - while ((inputLine = in.readLine()) != null) { - response.append(inputLine); - } - in.close(); - System.out.println("Response: " + response.toString()); - - ObjectMapper objectMapper = new ObjectMapper(); - JsonNode jsonNode = objectMapper.readTree(response.toString()); - - String resultStatus = jsonNode.get("ResultStatus").asText(); - - if (!resultStatus.isEmpty() && resultStatus.equals("false")) { - erpData.setStatus(false); - erpPostDataRepository.save(erpData); - } - - } else { - System.out.println("GET request failed."); - } - - } catch (Exception e) { - e.printStackTrace(); - } - }*/ + /* + * public void postEPDataToERP(ExtraPayments payment, TransactionResponse res) { + * RestTemplate restTemplate = new RestTemplate(); + * erpPostData erpData = new erpPostData(); + * + * SimpleDateFormat outputFormat = new SimpleDateFormat("dd/MM/yyyy"); + * String txDate = outputFormat.format(payment.getCdate()); + * String assesNo = LocalDate.now().getYear() + "/COMM/ED/" + + * res.getBookingId(); + * + * Map data = new TreeMap<>(); + *//* static mandatory input to be sent *//* + * data.put("serviceId", "getOtherCollection"); + * data.put("COLLECTION_TYPE", "Community Hall"); + * data.put("TOTALTRANSACTIONCODE", "450310000"); + * // /end of static/ + * // /unique data to be send/ + * data.put("ASSESSMENTNO", assesNo); + * data.put("UNIQUERECEIPTID", res.getBookingId()); + * data.put("TRANSACTIONNO", payment.getTransactionId()); + * data.put("TRANSACTIONREFNO", res.getTpslTxnId()); + * data.put("TRANSACTIONDATE", txDate); //payment date format dd/mm/yyyy + * -> 19/02/2025 + * data.put("TOTALTRANSACTIONAMOUNT", payment.getAmountReceived()); + * + * data.put("MSTRCODEONE", "061"); + * data.put("SPLITAMOUNTONE", 0); + * data.put("MSTRCODETWO", "062"); + * data.put("SPLITAMOUNTTWO", payment.getAmountReceived()); + * data.put("MSTRCODETHREE", "063"); + * data.put("SPLITAMOUNTTHREE", 0); + * // /Amount Collected from party/ + * data.put("PARTYNAME", + * payment.getBookingDetails().getUsers().getName()); + * data.put("PARTYADDRESS", + * payment.getBookingDetails().getUsers().getStreet() + "," + + * payment.getBookingDetails().getUsers().getArea() + "," + + * payment.getBookingDetails().getUsers().getLocation() + "," + + * payment.getBookingDetails().getUsers().getPinCode()); + * data.put("PARTYMOBILE", + * payment.getBookingDetails().getUsers().getMobileNo()); + *//* end *//* + * System.out.println(data); + * System.out.println(appConfig.getCommErpUrl()); + * // ResponseEntity stringResponseEntity = + * restTemplate.postForEntity(appConfig.getErpUrl(), data, + * String.class); + * // System.out.println(stringResponseEntity.getBody()); + * + * erpData.setTx_id(payment.getTransactionId()); + * erpData.setBooking_det_booking_id(res.getBookingId()); + * erpData.setStatus(true); + * erpData.setCdate(LocalDate.now()); + * erpData.setPay_status(2); + * erpPostDataRepository.save(erpData); + * + * UriComponentsBuilder builder = + * UriComponentsBuilder.fromHttpUrl(appConfig.getCommErpUrl()) + * ; + * for (Map.Entry entry : data.entrySet()) { + * builder.queryParam(entry.getKey(), entry.getValue()); + * } + * + * String urlMsg = builder.toUriString(); + * System.out.println(urlMsg); + * + * try { + * HttpURLConnection connection = null; + * + * URL url = new URL(urlMsg); + * connection = (HttpURLConnection) url.openConnection(); + * connection.setRequestMethod("GET"); + * + * int responseCode = connection.getResponseCode(); + * // response=responseCode+""; + * System.out.println("Response Code: " + responseCode); + * + * if (responseCode == HttpURLConnection.HTTP_OK) { // 200 OK + * BufferedReader in = new BufferedReader(new + * InputStreamReader(connection.getInputStream())); + * String inputLine; + * StringBuilder response = new StringBuilder(); + * while ((inputLine = in.readLine()) != null) { + * response.append(inputLine); + * } + * in.close(); + * System.out.println("Response: " + response.toString()); + * + * ObjectMapper objectMapper = new ObjectMapper(); + * JsonNode jsonNode = + * objectMapper.readTree(response.toString()); + * + * String resultStatus = + * jsonNode.get("ResultStatus").asText(); + * + * if (!resultStatus.isEmpty() && + * resultStatus.equals("false")) { + * erpData.setStatus(false); + * erpPostDataRepository.save(erpData); + * } + * + * } else { + * System.out.println("GET request failed."); + * } + * + * } catch (Exception e) { + * e.printStackTrace(); + * } + * } + */ @PostMapping(value = "/updatetransaction") - public String updatetransaction(Model model, @RequestParam(required = false) String txansactionId, @RequestParam(required = false) String msg) throws NoSuchAlgorithmException { + public String updatetransaction(Model model, @RequestParam(required = false) String txansactionId, + @RequestParam(required = false) String msg) throws NoSuchAlgorithmException { Optional transactionresponse = transactionResRepo.findByTxansactionId(txansactionId); TransactionResponse transactionres = transactionresponse.get(); @@ -581,7 +641,6 @@ public String response(Model model, @RequestParam(required = false) String msg) payment.setTransactionId(response.getTxansactionId()); double amount = 0; - for (int i = 0; i < res.length; i++) { if (i == res.length - 1) { c = c + salt; @@ -598,7 +657,7 @@ public String response(Model model, @RequestParam(required = false) String msg) response.setTpslTxnId(res[i]); response.setAmount(res[6]); response.setTxansactionId(res[3]); - //String[] tDate = res[8].split(" "); + // String[] tDate = res[8].split(" "); response.setDate(res[8]); } } @@ -607,7 +666,7 @@ public String response(Model model, @RequestParam(required = false) String msg) amount = Double.parseDouble(response.getAmount()); } catch (Exception e) { // TODO: handle exception - //System.out.println("payment Controller lineNo-67"); + // System.out.println("payment Controller lineNo-67"); } payment.setAmountReceived(amount); payment.setPaymentStatus("Not Completed"); @@ -630,7 +689,7 @@ public String response(Model model, @RequestParam(required = false) String msg) // System.out.println(response.toString()); model.addAttribute("bookingsDetails", bookingsDetails); // Add single BookingDetails object - //System.out.println(save.toString()); + // System.out.println(save.toString()); paymentRepo.save(payment); return "success"; } else { @@ -639,7 +698,8 @@ public String response(Model model, @RequestParam(required = false) String msg) } @PostMapping(value = "/refundcompleted") - public String refundCompleted(Model model, @RequestParam String txansactionId, @RequestParam(required = false) String msg) throws NoSuchAlgorithmException { + public String refundCompleted(Model model, @RequestParam String txansactionId, + @RequestParam(required = false) String msg) throws NoSuchAlgorithmException { Optional transactionresponse = transactionResRepo.findByTxansactionId(txansactionId); if (transactionresponse.isPresent()) { TransactionResponse transactionres = transactionresponse.get(); diff --git a/src/main/java/com/gcc/communityHall/paymentService/repository/TransactionResponseRepository.java b/src/main/java/com/gcc/communityHall/paymentService/repository/TransactionResponseRepository.java index 3ef7b23..86eb65c 100644 --- a/src/main/java/com/gcc/communityHall/paymentService/repository/TransactionResponseRepository.java +++ b/src/main/java/com/gcc/communityHall/paymentService/repository/TransactionResponseRepository.java @@ -11,51 +11,71 @@ import org.springframework.stereotype.Repository; import com.gcc.communityHall.paymentService.entity.TransactionResponse; +@Repository +public interface TransactionResponseRepository extends JpaRepository { + Optional findByBookingId(int bookingId); + List findByuserId(String userId); + Optional findByTxansactionId(String txansactionId); -@Repository -public interface TransactionResponseRepository extends JpaRepository{ - - Optional findByBookingId(int bookingId); - List findByuserId(String userId); - Optional findByTxansactionId(String txansactionId ); + Optional findByTxansactionIdAndStatusCode(String txansactionId, String statusCode); - Optional findByTxansactionIdAndStatusCode(String txansactionId,String statusCode ); - Optional findByBookingIdAndStatusCode(int bookingId, String statusCode); - Optional findByBookingIdAndTxansactionIdAndStatusCode(int bookingId,String txansactionId, String statusCode); + Optional findByBookingIdAndStatusCode(int bookingId, String statusCode); + Optional findByBookingIdAndTxansactionIdAndStatusCode(int bookingId, String txansactionId, + String statusCode); @Query(value = "SELECT tr.booking_id, tr.hall_id, tr.amount, tr.status_code, tr.txansaction_id, tr.user_id " + -// ", p.payment_status " + + // ", p.payment_status " + "FROM transaction_response tr " + "JOIN hall_details hd ON tr.hall_id = hd.hall_id " + -// "LEFT JOIN payments p ON tr.booking_id = p.booking_details_booking_id " + + // "LEFT JOIN payments p ON tr.booking_id = p.booking_details_booking_id " + "LEFT JOIN booking_details bd ON tr.booking_id = bd.booking_id " + "WHERE DATE(STR_TO_DATE(tr.cdate, '%Y-%m-%d')) >= STR_TO_DATE(:fromDate, '%Y-%m-%d') " + -// "WHERE DATE(STR_TO_DATE(tr.cdate, '%d-%m-%Y %H:%i:%s')) >= STR_TO_DATE(:fromDate, '%Y-%m-%d') " + + // "WHERE DATE(STR_TO_DATE(tr.cdate, '%d-%m-%Y %H:%i:%s')) >= + // STR_TO_DATE(:fromDate, '%Y-%m-%d') " + "AND DATE(STR_TO_DATE(tr.cdate, '%Y-%m-%d')) <= STR_TO_DATE(:toDate, '%Y-%m-%d') " + "AND (:bookingId IS NULL OR tr.booking_id = :bookingId) " + "AND (:hallId IS NULL OR tr.hall_id = :hallId)", nativeQuery = true) List getTransactionResponseByBookingId(@Param("fromDate") String fromDate, - @Param("toDate") String toDate, - @Param("bookingId") Long bookingId, - @Param("hallId") Long hallId); - - - -// @Transactional -// @Query (value = "UPDATE transaction_response SET amount = :amount, booking_id =:booking_id , date = :date, hall_id = :hall_id, response = :response, status_code = :status_code, tpsl_txn_id = :tpsl_txn_id, txansaction_id = :txansaction_id, user_id = :user_id WHERE (id = :id)",nativeQuery = true) -// void updateTransactionResponse ( @Param("id") Integer id, @Param("amount") String amount, @Param("booking_id") int booking_id ,@Param("date" ) String date,@Param("hall_id" ) int hall_id ,@Param("response")String response,@Param("status_code")String status_code,@Param("tpsl_txn_id")String tpsl_txn_id,@Param("txansaction_id")String txansaction_id,@Param("user_id")String user_id ); - -// TransactionResponse saveTransactionResponse(Integer id, String amount, int bookingId, String date, int hallId, String response, -// String statusCode, String tpslTxnId, String txansactionId, String userId); - -// @Query(value = "INSERT INTO transaction_response ('id','amount','booking_id','date','hall_id','response','status_code','tpsl_txn_id','txansaction_id','user_id') VALUES (:id, :amount, :booking_id, :date, :hall_id, :response, :status_code, :tpsl_txn_id, :txansaction_id, :user_id)", nativeQuery = true) -// void saveTransactionResponse(@Param("id") int id, @Param("amount") String amount, @Param("booking_id") int booking_id ,@Param("date" ) String date,@Param("hall_id" ) int hall_id ,@Param("response")String response,@Param("status_code")String status_code,@Param("tpsl_txn_id")String tpsl_txn_id,@Param("txansaction_id")String txansaction_id,@Param("user_id")String user_id ); -// - //@Query (value = "UPDATE transaction_response SET 'amount' = :amount, 'booking_id' =:booking_id , 'date' = :date, 'hall_id' = :hall_id, 'response' = :response, 'status_code' = :status_code, 'tpsl_txn_id' = :tpsl_txn_id, 'txansaction_id' = :txansaction_id, 'user_id' = :user_id WHERE ('id' = :id)", nativeQuery = true) + @Param("toDate") String toDate, + @Param("bookingId") Long bookingId, + @Param("hallId") Long hallId); + + // @Transactional + // @Query (value = "UPDATE transaction_response SET amount = :amount, booking_id + // =:booking_id , date = :date, hall_id = :hall_id, response = :response, + // status_code = :status_code, tpsl_txn_id = :tpsl_txn_id, txansaction_id = + // :txansaction_id, user_id = :user_id WHERE (id = :id)",nativeQuery = true) + // void updateTransactionResponse ( @Param("id") Integer id, @Param("amount") + // String amount, @Param("booking_id") int booking_id ,@Param("date" ) String + // date,@Param("hall_id" ) int hall_id ,@Param("response")String + // response,@Param("status_code")String status_code,@Param("tpsl_txn_id")String + // tpsl_txn_id,@Param("txansaction_id")String + // txansaction_id,@Param("user_id")String user_id ); + + // TransactionResponse saveTransactionResponse(Integer id, String amount, int + // bookingId, String date, int hallId, String response, + // String statusCode, String tpslTxnId, String txansactionId, String userId); + + // @Query(value = "INSERT INTO transaction_response + // ('id','amount','booking_id','date','hall_id','response','status_code','tpsl_txn_id','txansaction_id','user_id') + // VALUES (:id, :amount, :booking_id, :date, :hall_id, :response, :status_code, + // :tpsl_txn_id, :txansaction_id, :user_id)", nativeQuery = true) + // void saveTransactionResponse(@Param("id") int id, @Param("amount") String + // amount, @Param("booking_id") int booking_id ,@Param("date" ) String + // date,@Param("hall_id" ) int hall_id ,@Param("response")String + // response,@Param("status_code")String status_code,@Param("tpsl_txn_id")String + // tpsl_txn_id,@Param("txansaction_id")String + // txansaction_id,@Param("user_id")String user_id ); + // + // @Query (value = "UPDATE transaction_response SET 'amount' = :amount, + // 'booking_id' =:booking_id , 'date' = :date, 'hall_id' = :hall_id, 'response' + // = :response, 'status_code' = :status_code, 'tpsl_txn_id' = :tpsl_txn_id, + // 'txansaction_id' = :txansaction_id, 'user_id' = :user_id WHERE ('id' = :id)", + // nativeQuery = true) @Query(value = "SELECT tr.id, tr.amount, tr.booking_id, tr.hall_id, tr.response, tr.status_code, " + "tr.tpsl_txn_id, tr.txansaction_id, tr.user_id, bd.booking_date " + @@ -64,10 +84,12 @@ public interface TransactionResponseRepository extends JpaRepository> getTransactionResponseByStatus(String status); - - @Query(value = "SELECT tr.id, tr.amount, tr.booking_id, tr.hall_id, tr.response, tr.tpsl_txn_id, tr.txansaction_id, tr.cdate, " + + @Query(value = "SELECT tr.id, tr.amount, tr.booking_id, tr.hall_id, tr.response, tr.tpsl_txn_id, tr.txansaction_id, tr.cdate, " + + "tr.user_id, bd.booking_date FROM transaction_response tr " + "INNER JOIN booking_details bd ON tr.booking_id = bd.booking_id " + "WHERE tr.status_code = 'temp' AND tr.cdate < DATE_SUB(NOW(), INTERVAL 1 HOUR);", nativeQuery = true) List> getTransResBycdateandStatus(String status); + + boolean existsByBookingId(int bookingId); } diff --git a/src/main/java/com/gcc/communityHall/repository/BookingDetailsRepository.java b/src/main/java/com/gcc/communityHall/repository/BookingDetailsRepository.java index 50e8e44..4af9475 100644 --- a/src/main/java/com/gcc/communityHall/repository/BookingDetailsRepository.java +++ b/src/main/java/com/gcc/communityHall/repository/BookingDetailsRepository.java @@ -1712,4 +1712,43 @@ public interface BookingDetailsRepository extends JpaRepository getCounterWiseBookingList(String fromDate, String toDate); + + @Query(value = "SELECT " + + " u.user_id as userId," + + " u.name as UserName," + + " u.mobile_no as UserMobile," + + " u. usertype as UserType," + + " CONCAT(" + + " IFNULL(u.doorno,''), ', ', " + + " IFNULL(u.street,''), ', ', " + + " IFNULL(u.area,''), ', ', " + + " IFNULL(u.location,''), ' - ', " + + " IFNULL(u.pin_code,'') " + + " ) AS UserAddress, " + + "hd.hall_name as hallName," + + " CONCAT(" + + " IFNULL(hd.door_no,''), ', ', " + + " IFNULL(hd.street,''), ', ', " + + " IFNULL(hd.area,''), ', ', " + + " IFNULL(hd.city,''), ' - ', " + + " IFNULL(hd.pin_code,'') " + + " ) AS HallAddress, " + + " hd.hall_incharge_name as CareTakerName," + + " hd.hall_incharge_no as CareTakerMobile," + + " bd.booking_id as bookingId," + + " bd.booking_date as bookingDate," + + " bd.start_date as start_date," + + " bd.end_date as end_date," + + "bd.deposit_amount as depositAmount," + + "bd.gst as gst," + + "bd.hall_amount as hallAmount," + + " bd.amount_received as totalAmount " + + "FROM booking_details bd " + + "INNER JOIN hall_request_details hrd " + + "ON hrd.booking_id = bd.booking_id " + + "LEFT JOIN hall_details hd ON hd.hall_id=bd.hall_details_hall_id " + + "LEFT JOIN users u ON u.user_id=bd.users_user_id " + + "WHERE bd.booking_id = :bookingId " + + "AND hrd.booking_status = 'APPROVED'", nativeQuery = true) + List> findApprovedBookingWithHallRequest(@Param("bookingId") int bookingId); } diff --git a/src/main/java/com/gcc/communityHall/repository/HallRequestDetailsRepository.java b/src/main/java/com/gcc/communityHall/repository/HallRequestDetailsRepository.java new file mode 100644 index 0000000..dbeca2a --- /dev/null +++ b/src/main/java/com/gcc/communityHall/repository/HallRequestDetailsRepository.java @@ -0,0 +1,39 @@ +package com.gcc.communityHall.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; +import org.springframework.data.jpa.repository.Query; + +import com.gcc.communityHall.entity.HallRequestDetails; + +@Repository +public interface HallRequestDetailsRepository extends JpaRepository { + + @Query(value =" SELECT r.*, b.*, h.*, u.* "+ + " FROM hall_request_details r "+ + " JOIN booking_details b ON r.booking_id = b.booking_id "+ + " JOIN hall_details h ON b.hall_details_hall_id = h.hall_id "+ + " JOIN users u ON b.users_user_id = u.user_id "+ + " WHERE b.booking_status = 'PENDING'", nativeQuery = true) + List findPendingRequests(); + + @Query(""" + SELECT hrd FROM HallRequestDetails hrd + JOIN FETCH hrd.bookingDetails b + JOIN FETCH b.hallDetails + JOIN FETCH b.users + WHERE b.bookingStatus IN ('APPROVED', 'WAITING_FOR_NOC') + """) + List findApprovedRequests(); + + @Query(""" + SELECT hrd FROM HallRequestDetails hrd + JOIN FETCH hrd.bookingDetails b + JOIN FETCH b.hallDetails + JOIN FETCH b.users + WHERE b.bookingStatus = 'REJECTED' + """) + List findRejectedRequests(); +} diff --git a/src/main/java/com/gcc/communityHall/repository/PaymentsRepository.java b/src/main/java/com/gcc/communityHall/repository/PaymentsRepository.java index 11df3bd..920d757 100644 --- a/src/main/java/com/gcc/communityHall/repository/PaymentsRepository.java +++ b/src/main/java/com/gcc/communityHall/repository/PaymentsRepository.java @@ -1,6 +1,5 @@ package com.gcc.communityHall.repository; - import com.gcc.communityHall.entity.Payments; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; @@ -12,17 +11,21 @@ import java.util.Optional; @Repository -public interface PaymentsRepository extends JpaRepository { +public interface PaymentsRepository extends JpaRepository { - @Query(value = "SELECT * FROM payments WHERE payment_status in ('paid') ",nativeQuery = true) + @Query(value = "SELECT * FROM payments WHERE payment_status in ('paid') ", nativeQuery = true) List getPaymentlist(); - @Query(value="SELECT p.* " - + "FROM payments p " - + "JOIN booking_details b ON p.booking_details_booking_id = b.booking_id " - + "JOIN hall_details h ON b.hall_details_hall_id = h.hall_id " - + "WHERE h.zone = :zone", nativeQuery = true) + + @Query(value = "SELECT p.* " + + "FROM payments p " + + "JOIN booking_details b ON p.booking_details_booking_id = b.booking_id " + + "JOIN hall_details h ON b.hall_details_hall_id = h.hall_id " + + "WHERE h.zone = :zone", nativeQuery = true) List getPaymentListByzone(@Param("zone") String zone); - //List findAllWithBookingDetailsAndUsers(); - @Query(value = "select * from payments where booking_details_booking_id=?",nativeQuery = true) + + // List findAllWithBookingDetailsAndUsers(); + @Query(value = "select * from payments where booking_details_booking_id=?", nativeQuery = true) Payments findByBookingId(int bookingId); + + boolean existsByBookingDetails_BookingId(int bookingId); } \ No newline at end of file diff --git a/src/main/java/com/gcc/communityHall/repository/ReasonMasterRepository.java b/src/main/java/com/gcc/communityHall/repository/ReasonMasterRepository.java index 2faa6c4..56424cf 100644 --- a/src/main/java/com/gcc/communityHall/repository/ReasonMasterRepository.java +++ b/src/main/java/com/gcc/communityHall/repository/ReasonMasterRepository.java @@ -9,7 +9,10 @@ import org.springframework.stereotype.Repository; import com.gcc.communityHall.entity.ReasonMaster; @Repository -public interface ReasonMasterRepository extends JpaRepository { +public interface ReasonMasterRepository extends JpaRepository { ReasonMaster findByReason(String reason); + + @Query(value = "select * from reason_master where is_active =1 and is_delete=0 ", nativeQuery = true) + List getAllReasonsWithStatus(); } diff --git a/src/main/java/com/gcc/communityHall/service/BookingService.java b/src/main/java/com/gcc/communityHall/service/BookingService.java index 6fd64e5..794b0ee 100644 --- a/src/main/java/com/gcc/communityHall/service/BookingService.java +++ b/src/main/java/com/gcc/communityHall/service/BookingService.java @@ -1,6 +1,5 @@ package com.gcc.communityHall.service; - import java.time.LocalDate; import java.util.Date; import java.util.List; @@ -16,213 +15,254 @@ import com.gcc.communityHall.entity.BookingDetails.BookingStatus; import com.gcc.communityHall.entity.BookingDetails.RefundStatus; import com.gcc.communityHall.entity.EbDetails; import com.gcc.communityHall.entity.GccBlockingDate; +import com.gcc.communityHall.entity.HallRequestDetails; public interface BookingService { - BookingDetails getBookingsById(int BookingId); - //ak - BookingDetails getBookingByRefId(String refId); - //ak - void migrateOldBookingsToRefId(); + BookingDetails getBookingsById(int BookingId); + + // ak + BookingDetails getBookingByRefId(String refId); + + // ak + void migrateOldBookingsToRefId(); + + BookingDetails updateBookingDetails(BookingDetails bd); + + public String confirmTheDateAndSlot(String fromDate, String toDate, int days, int fromStartingSlot, + int fromEndingSlot, int toStartingSlot, int toEndingSlot, int bookingId, int userId); + + public Map saveBookingDetails(Map formData); + + public BookingDetails updateBookingStatustoGCCBlocked(BookingDetails bookingDetails); + + public BookingDetails updateBookingStatus(int bookingId, BookingDetails.BookingStatus status, String comments); + + public BookingDetails updateBookingStatusById(int bookingId, BookingDetails.BookingStatus status, String comments); - BookingDetails updateBookingDetails(BookingDetails bd); + public EbDetails updateEbDetails(int bookingId, double startUnit, double endUnit, char status); - public String confirmTheDateAndSlot(String fromDate, String toDate, int days, int fromStartingSlot, int fromEndingSlot, int toStartingSlot, int toEndingSlot, int bookingId, int userId); + // typeOfCancel depends { } + String cancelBooking(int bookingId, BookingDetails.BookingStatus currentStatus, String comments); - public Map saveBookingDetails(Map formData); + public String confirmBooking(int bookingId); - public BookingDetails updateBookingStatustoGCCBlocked(BookingDetails bookingDetails); + public BookingDetails getBookingDetailsWithSettlement(int settlementId); - public BookingDetails updateBookingStatus(int bookingId, BookingDetails.BookingStatus status, String comments); + // sreeja + List getPresentsEventsByUserId(Integer hallId); - public BookingDetails updateBookingStatusById(int bookingId, BookingDetails.BookingStatus status, String comments); + List getPastsEventsByUserId(Integer hallId); - public EbDetails updateEbDetails(int bookingId, double startUnit, double endUnit, char status); + List getFuturesEventsByUserId(Integer hallId); - //typeOfCancel depends { } - String cancelBooking(int bookingId, BookingDetails.BookingStatus currentStatus, String comments); + List getSettlementList(Integer hallId); - public String confirmBooking(int bookingId); + public List getFilteredBookings(LocalDate fromDate, LocalDate toDate, List hallIds); - public BookingDetails getBookingDetailsWithSettlement(int settlementId); + public List getPastData(int hall_id); + 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[]); - //sreeja - List getPresentsEventsByUserId(Integer hallId); + public int checkUserBookinglimitation(int userId); - List getPastsEventsByUserId(Integer hallId); + List getAllBookingsByUserId(Integer userId); - List getFuturesEventsByUserId(Integer hallId); + List> getAllBookingEventsByUserId(Integer userId); - List getSettlementList(Integer hallId); + // List getAllBookingDetailsWithStatus(String fromDate, String + // toDate, String bookingStatus); - public List getFilteredBookings(LocalDate fromDate, LocalDate toDate, List hallIds); + // List getAllPaymentsDetails( String fromDate, String toDate); - public List getPastData(int hall_id); + List getBookingUserDetailsReport(String fromDate, String toDate); - 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[]); + List getBookingHallDetailsReport(String fromDate, String toDate); - public int checkUserBookinglimitation(int userId); + List getBlockedEvents(LocalDate fromDate, LocalDate toDate, List hallIds); - List getAllBookingsByUserId(Integer userId); + List> getOfflineBookings(); - List> getAllBookingEventsByUserId(Integer userId); + List getBookedslots(LocalDate fromDate, LocalDate endDate, List hallIdList); + BookingDetails updateCancelledBookingStatus(int bookingId, BookingStatus status, String comments); - //List getAllBookingDetailsWithStatus(String fromDate, String toDate, String bookingStatus); + BookingDetails updateRefundStatus(int bookingId, RefundStatus status); - //List getAllPaymentsDetails( String fromDate, String toDate); + // officer service + List getAllBookingDetailsByZone(String fromDate, String toDate, String zone); - List getBookingUserDetailsReport(String fromDate, String toDate); + List getAllBookingDetailsByZoneWithStatus(String fromDate, String toDate, String zone, + String bookingStatus); - List getBookingHallDetailsReport(String fromDate, String toDate); + List getAllPaymentsDetailsByZone(String fromDate, String toDate, String zone); - List getBlockedEvents(LocalDate fromDate, LocalDate toDate, List hallIds); + List getBookingHallDetailsReportByZone(String fromDate, String toDate, String zone); - List> getOfflineBookings(); + Optional updateBookingDatesAndCalendar(int bookingId, String startDate, String endDate); - List getBookedslots(LocalDate fromDate, LocalDate endDate, List hallIdList); + List getBookingHallDetailsReportByZone1(String fromDate, String toDate, String zone, Integer hallId); - BookingDetails updateCancelledBookingStatus(int bookingId, BookingStatus status, String comments); + List getGccBlockingEvents(String hallId); - BookingDetails updateRefundStatus(int bookingId, RefundStatus status); + int getBlockedHallCount(String blockingReason, Date startDate, Date endDate); - //officer service - List getAllBookingDetailsByZone(String fromDate, String toDate, String zone); + @Transactional + void cancelAllBookings(String fromDate, String toDate, List hallIdsList, + String reasonforblocking, List selectedBookings, String updatedBy, String[] descriptions, + MultipartFile[] documents); - List getAllBookingDetailsByZoneWithStatus(String fromDate, String toDate, String zone, String bookingStatus); + List findBookingDetailsByBookingId(Long bookingId); - List getAllPaymentsDetailsByZone(String fromDate, String toDate, String zone); + // admin dashboard + Map> getBookingStatistics(LocalDate fromDate, LocalDate toDate, String zone, + String division, Integer hallid, String userType); - List getBookingHallDetailsReportByZone(String fromDate, String toDate, String zone); + public List> getBookingDetailsByHallId(int hallId); - Optional updateBookingDatesAndCalendar(int bookingId, String startDate, String endDate); + // officer dashboard + Map> getOfficerDashboard(LocalDate fromDate, LocalDate toDate, String zone, + String division, Integer hallid, String userType); - List getBookingHallDetailsReportByZone1(String fromDate, String toDate, String zone, Integer hallId); + List> getHallDetailsForOfficer(Integer hallIid); + // List getAllPaymentsDetails(String fromDate, String toDate, String + // paymentStatus); + // admin reports - List getGccBlockingEvents(String hallId); + List getBookingDetailsByBookingDate(String fromDate, String toDate, String zone, String division, + Integer hallid); - int getBlockedHallCount(String blockingReason, Date startDate, Date endDate); + List getBookingDetailsByEventDate(String fromDate, String toDate, String zone, String division, + Integer hallid); - @Transactional - void cancelAllBookings(String fromDate, String toDate, List hallIdsList, - String reasonforblocking, List selectedBookings, String updatedBy, String[] descriptions, MultipartFile[] documents); + List getBookingDetailsByBookingDateWithStatus(String fromDate, String toDate, String bookingStatus, + String zone, String division, Integer hallid); - List findBookingDetailsByBookingId(Long bookingId); + List getBookingDetailsByEventDateWithStatus(String fromDate, String toDate, String bookingStatus, + String zone, String division, Integer hallid); - //admin dashboard - Map> getBookingStatistics(LocalDate fromDate, LocalDate toDate, String zone, String division, Integer hallid, String userType); + List getAllPaymentsDetails(String fromDate, String toDate, String paymentStatus, String zone, + String division, Integer hallid); - public List> getBookingDetailsByHallId(int hallId); + List getBookingHallDetailsReportByBookingDate(String fromDate, String toDate, String zone, String division, + Integer hallid); - //officer dashboard - Map> getOfficerDashboard(LocalDate fromDate, LocalDate toDate, String zone, String division, Integer hallid, String userType); + List getBookingHallDetailsReportByEventDate(String fromDate, String toDate, String zone, String division, + Integer hallid); - List> getHallDetailsForOfficer(Integer hallIid); - //List getAllPaymentsDetails(String fromDate, String toDate, String paymentStatus); - //admin reports + List getAllBookingsettlementDetailsByBookingDate(String fromDate, String toDate); - List getBookingDetailsByBookingDate(String fromDate, String toDate, String zone, String division, Integer hallid); + List getAllBookingsettlementDetailsByBookingDateWithStatus(String fromDate, String toDate, + String refundStatus); - List getBookingDetailsByEventDate(String fromDate, String toDate, String zone, String division, Integer hallid); + List getAllBookingsettlementDetailsByEventDate(String fromDate, String toDate); - List getBookingDetailsByBookingDateWithStatus(String fromDate, String toDate, String bookingStatus, String zone, String division, Integer hallid); + List getAllBookingsettlementDetailsByEventDateWithStatus(String fromDate, String toDate, + String refundStatus); - List getBookingDetailsByEventDateWithStatus(String fromDate, String toDate, String bookingStatus, String zone, String division, Integer hallid); + List getAllBookingDetailsBookingDateByZone(String fromDate, String toDate, String zone); - List getAllPaymentsDetails(String fromDate, String toDate, String paymentStatus, String zone, String division, Integer hallid); + List getAllBookingDetailsEventDateByZone(String fromDate, String toDate, String zone); - List getBookingHallDetailsReportByBookingDate(String fromDate, String toDate, String zone, String division, Integer hallid); + List getAllBookingDetailsBookingDateByZoneWithStatus(String fromDate, String toDate, String zone, + String bookingStatus); - List getBookingHallDetailsReportByEventDate(String fromDate, String toDate, String zone, String division, Integer hallid); + List getAllBookingDetailsEventDateByZoneWithStatus(String fromDate, String toDate, String zone, + String bookingStatus); - List getAllBookingsettlementDetailsByBookingDate(String fromDate, String toDate); + List getAllBookingsettlementDetailsByZoneByBookingDate(String fromDate, String toDate, String zone); - List getAllBookingsettlementDetailsByBookingDateWithStatus(String fromDate, String toDate, String refundStatus); + List getAllBookingsettlementDetailsByZoneByEventDate(String fromDate, String toDate, String zone); - List getAllBookingsettlementDetailsByEventDate(String fromDate, String toDate); + List getAllBookingsettlementDetailsByZoneByBookingDateWithStatus(String fromDate, String toDate, + String zone, String refundStatus); - List getAllBookingsettlementDetailsByEventDateWithStatus(String fromDate, String toDate, String refundStatus); + List getAllBookingsettlementDetailsByZoneByEventDateWithStatus(String fromDate, String toDate, + String zone, String refundStatus); - List getAllBookingDetailsBookingDateByZone(String fromDate, String toDate, String zone); + List getBookingHallDetailsReportByZoneByBookingDate(String fromDate, String toDate, String zone); - List getAllBookingDetailsEventDateByZone(String fromDate, String toDate, String zone); + List getBookingHallDetailsReportByZoneByEventDate(String fromDate, String toDate, String zone); - List getAllBookingDetailsBookingDateByZoneWithStatus(String fromDate, String toDate, String zone, String bookingStatus); + List getBookingHallDetailsReportByZoneByBookingDateHallname(String fromDate, String toDate, String zone, + Integer hallId); - List getAllBookingDetailsEventDateByZoneWithStatus(String fromDate, String toDate, String zone, String bookingStatus); + List getBookingHallDetailsReportByZoneByEventDateHallname(String fromDate, String toDate, String zone, + Integer hallId); - List getAllBookingsettlementDetailsByZoneByBookingDate(String fromDate, String toDate, String zone); + BookingDetails saveebdetails(int bookingId, double startingReading, MultipartFile startingReadingimage); - List getAllBookingsettlementDetailsByZoneByEventDate(String fromDate, String toDate, String zone); + String confirmStateBooking(int bookingId); - List getAllBookingsettlementDetailsByZoneByBookingDateWithStatus(String fromDate, String toDate, String zone, String refundStatus); + String uploadNOCFile(MultipartFile file, int bookingId); - List getAllBookingsettlementDetailsByZoneByEventDateWithStatus(String fromDate, String toDate, String zone, String refundStatus); + // gccapps + List getApprovedBookingDetails(); - List getBookingHallDetailsReportByZoneByBookingDate(String fromDate, String toDate, String zone); + List getRejectedBookingDetails(); - List getBookingHallDetailsReportByZoneByEventDate(String fromDate, String toDate, String zone); + List getAllPaymentsDetails(String fromDate, String toDate); - List getBookingHallDetailsReportByZoneByBookingDateHallname(String fromDate, String toDate, String zone, Integer hallId); + List getPastsEvents(); - List getBookingHallDetailsReportByZoneByEventDateHallname(String fromDate, String toDate, String zone, Integer hallId); + List getPresentsEvents(); - BookingDetails saveebdetails(int bookingId, double startingReading, MultipartFile startingReadingimage); + List getFuturesEvents(); - String confirmStateBooking(int bookingId); + List getSettlementApprovedList(); - String uploadNOCFile(MultipartFile file, int bookingId); + List> getHallDetails(Integer hall_id); - //gccapps - List getApprovedBookingDetails(); + List getWaitingforNOCapproval(); - List getRejectedBookingDetails(); + List getAllExtraPaymentsDetails(String fromDate, String toDate, String paymentStatus, String zone, + String division, Integer hallid); - List getAllPaymentsDetails(String fromDate, String toDate); + // developer + List getTransactionresponse(String fromDate, String toDate, Long bookingId, Long hallId); - List getPastsEvents(); + List getRefundResponse(String fromDate, String toDate, Long bookingId); - List getPresentsEvents(); + List getBookingCalendarDetails(String fromDate, String toDate, Long bookingId, String hallName); - List getFuturesEvents(); + List getBookingsByDateAndHall(String bookingDate, Long hallId); - List getSettlementApprovedList(); + BookingDetails updateRefundStatusScheduler(int bookingId, RefundStatus status); - List> getHallDetails(Integer hall_id); + List getCounterWiseBookingCount(String fromDate, String toDate); - List getWaitingforNOCapproval(); + List getHallWiseBookingDetails(String fromDate, String toDate, String CounterId); - List getAllExtraPaymentsDetails(String fromDate, String toDate, String paymentStatus, String zone, String division, Integer hallid); + List getBookingDetailsForAllHalls(String fromDate, String toDate, String CounterId, Integer hallid); - //developer - List getTransactionresponse(String fromDate, String toDate, Long bookingId, Long hallId); + List getCounterWiseBookingDetails(String fromDate, String toDate); - List getRefundResponse(String fromDate, String toDate, Long bookingId); + List getZoneWiseBookingList(String fromDate, String toDate); - List getBookingCalendarDetails(String fromDate, String toDate, Long bookingId, String hallName); + List getAllHallWiseBookingList(String fromDate, String toDate); - List getBookingsByDateAndHall(String bookingDate, Long hallId); + List getAllCounterWiseBookingList(String fromDate, String toDate); - BookingDetails updateRefundStatusScheduler(int bookingId, RefundStatus status); + // ak + List getSettlementInitiatedReport(String fromDate, String toDate); - List getCounterWiseBookingCount(String fromDate, String toDate); + public String saveHallRequestDetails(String fromDate, String toDate, int startingSlot, + int endingSlot, String relationship, String reason, int hallId, int userId, + String orgType, String eventDesc, String offAddress, MultipartFile bonafide); - List getHallWiseBookingDetails(String fromDate, String toDate, String CounterId); + List getPendingGovtRequests(); - List getBookingDetailsForAllHalls(String fromDate, String toDate, String CounterId, Integer hallid); + List getApprovedGovtRequests(); - List getCounterWiseBookingDetails(String fromDate, String toDate); + List getRejectedGovtRequests(); - List getZoneWiseBookingList(String fromDate, String toDate); + void updateGovtRequest(int reqId, String action, double discountPercentage, boolean nocRequired); - List getAllHallWiseBookingList(String fromDate, String toDate); + List> getvphcollectionpending(int bookingId); - List getAllCounterWiseBookingList(String fromDate, String toDate); - //ak - List getSettlementInitiatedReport(String fromDate, String toDate); + boolean isPaymentAlreadyDoneOrInitiated(int bookingId); } 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 208c42d..28d1919 100644 --- a/src/main/java/com/gcc/communityHall/service/Impl/BookingServiceImpl.java +++ b/src/main/java/com/gcc/communityHall/service/Impl/BookingServiceImpl.java @@ -3,6 +3,7 @@ package com.gcc.communityHall.service.Impl; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; +import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.text.ParseException; @@ -46,6 +47,7 @@ import com.gcc.communityHall.entity.GccBlockingHistory; import com.gcc.communityHall.entity.GccblockingDocuments; import com.gcc.communityHall.entity.HallDetails; import com.gcc.communityHall.entity.HallDetailsConcession; +import com.gcc.communityHall.entity.HallRequestDetails; import com.gcc.communityHall.entity.ReasonDocumentMaster; import com.gcc.communityHall.entity.ReasonMaster; import com.gcc.communityHall.entity.Settlement; @@ -72,6 +74,8 @@ import com.gcc.communityHall.repository.ReasonMasterRepository; import com.gcc.communityHall.repository.SettlementHistoryRepository; import com.gcc.communityHall.repository.SettlementRepository; import com.gcc.communityHall.repository.UsersRepository; +import com.gcc.communityHall.repository.HallRequestDetailsRepository; +import com.gcc.communityHall.repository.PaymentsRepository; import com.gcc.communityHall.service.ApplicationLogService; import com.gcc.communityHall.service.BookingService; import com.gcc.communityHall.service.DiscountRangeService; @@ -163,6 +167,12 @@ public class BookingServiceImpl implements BookingService { @Autowired private TransRefundResRepository transRefundResRepository; + @Autowired + private HallRequestDetailsRepository hallRequestDetailsRepository; + + @Autowired + private PaymentsRepository paymentsRepository; + @Value("${file.upload.directory}") private String uploadDirectory; @@ -242,6 +252,16 @@ public class BookingServiceImpl implements BookingService { @Override public BookingDetails updateBookingStatus(int bookingId, BookingDetails.BookingStatus status, String comments) { Optional booking = bookingDetailsRepository.findById(bookingId); + String apikey = "5c995535-6244-11f0-98fc-02c8a5e042bd"; + String from = "919445061913"; + + String hallName, userName, endDate; + + // String[] numbers = { "9123565217", "9789091845", "9894935693", "8667881667" + // }; // for testing purpose + String[] numbers = { "9123565217", "9789091845", "9894935693", + "9444173345", "9994697909", "9176617754", "9445190998", "9381013498", + "9789977111" }; if (booking.isPresent()) { BookingDetails book = booking.get(); /* @@ -260,6 +280,39 @@ public class BookingServiceImpl implements BookingService { book.setBookingStatus(status); book.setComments(comments); BookingDetails bookings = bookingDetailsRepository.save(book); + + if ("APPROVED".equals(status)) { + for (String mobNo : numbers) { + + hallName = bookings.getHallDetails().getHallName(); + userName = bookings.getUsers().getName(); + // Format endDate from yyyy-MM-dd to dd-MM-yyyy + String rawEndDate = bookings.getEndDate(); + try { + LocalDate date = LocalDate.parse(rawEndDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")); + endDate = date.format(DateTimeFormatter.ofPattern("dd-MM-yyyy")); + } catch (Exception e) { + endDate = rawEndDate; // Fallback to original if parsing fails + } + + String placeholders = ""; + try { + placeholders = URLEncoder.encode(userName + "|~|" + hallName + "|~|" + endDate, "UTF-8"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + + String whatsappMsg = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?apikey=" + apikey + "&from=" + + from + + "&to=91" + mobNo + "" + + "&type=template&templateid=2815237&placeholders=" + placeholders + ""; + + System.out.println(whatsappMsg + ":" + mobNo); + + whatsappMsgServiceImpl.sendMsg(whatsappMsg); + } + } + return bookings; } return null; @@ -280,7 +333,7 @@ public class BookingServiceImpl implements BookingService { Optional bookingDet = bookingDetailsRepository.findById(bookingId); if (!bookingDet.isPresent()) { - // Handle invalid booking ID + // Handle invalid booking I D return "Invalid booking ID"; } bookingDetails = bookingDet.get(); @@ -471,13 +524,21 @@ public class BookingServiceImpl implements BookingService { public String processBookingStatusAndSendMessages(BookingDetails bookingDetails, String hallName, String userName, LocalDate endDate) { try { + + String apikey = "5c995535-6244-11f0-98fc-02c8a5e042bd"; + String from = "919445061913"; + String reason = bookingDetails.getReason(); ReasonMaster reasonDetails = reasonMasterRepository.findByReason(reason); String reasonCode = (reasonDetails != null && reasonDetails.getReasoncode() != null) ? reasonDetails.getReasoncode() : ""; - String[] numbers = { "9123565217", "9789091845", "9894935693", "9444173345", "9840562783", "9842042722", "9176617754" }; + // String[] numbers = { "9123565217", "9789091845", "9894935693", "8667881667" + // }; // for testing purpose + String[] numbers = { "9123565217", "9789091845", "9894935693", + "9444173345", "9994697909", "9176617754", "9445190998", "9381013498", + "9789977111" }; String bookingconfirmationmsg, urlString, whatsupmsg, bookingmsg; @@ -505,18 +566,27 @@ public class BookingServiceImpl implements BookingService { String encodedHN = URLEncoder.encode(hallName, StandardCharsets.UTF_8); - // String endDateStr = endDate+"-%20Test%20message%20please%20ignore"; + // String endDateStr = endDate+"-%20Test%20message%20please%20ignore"; + + String msg = "A%20new%20" + encodedHN + "%20booking%20has%20been%20successfully%20made%20by%20" + + userName + "%20for%20" + endDate + "."; - String msg = "A%20new%20"+ encodedHN + "%20booking%20has%20been%20successfully%20made%20by%20"+ userName +"%20for%20" + endDate+ "."; - String encodedFooter = URLEncoder.encode("- GCC IT Cell", StandardCharsets.UTF_8); bookingmsg = "https://mediaapi.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ" + - "&send_to=" + mobNo + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg="+msg+"&isTemplate=true&footer="+encodedFooter+""; - + "&send_to=" + mobNo + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=" + msg + + "&isTemplate=true&footer=" + encodedFooter + ""; + + System.out.println(bookingmsg + ":" + mobNo); + + String placeholders = URLEncoder.encode(hallName + "|~|" + userName + "|~|" + endDate, "UTF-8"); - System.out.println(bookingmsg+":"+mobNo); + String whatsappMsg = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?apikey=" + apikey + "&from=" + + from + "&to=91" + mobNo + "" + + "&type=template&templateid=2815236&placeholders=" + placeholders + ""; - whatsappMsgServiceImpl.sendMsg(bookingmsg); + System.out.println(whatsappMsg + ":" + mobNo); + + whatsappMsgServiceImpl.sendMsg(whatsappMsg); } // whatsappMsgServiceImpl.sendSMS(urlString); return "Waiting For NOC Documents"; @@ -817,10 +887,12 @@ public class BookingServiceImpl implements BookingService { } @Override + @Transactional public Map saveBookingDetails(Map formData) { Map hs = new HashMap<>(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); BookingDetails bookingDetails = null; + List uploadedDocs = new ArrayList<>(); Integer userId = userSession.getUserId(); String counterId = userSession.getCounter(); @@ -926,7 +998,7 @@ public class BookingServiceImpl implements BookingService { hs.put("reasoncode", reasoncode); HallDetailsConcession governmentevents = hallDetailsConcessionRepo .findbyhallId(hallDetails.getHallId()); - if (reasoncode.equals("SGE")) { + if (reasoncode.equals("CGE")) { discountAmount = (governmentevents.getFulldayhallamount() * hallDetails.getSGEdiscount()) / 100; // hallAmount = governmentevents.getFulldayhallamount(); hallAmount = hallAmount - discountAmount; @@ -946,7 +1018,7 @@ public class BookingServiceImpl implements BookingService { bookingDetails.setAmountReceived(truncatedTotalAmount); hs.put("additionalcharges", additionalcharges); hs.put("totalAmount", truncatedTotalAmount); - } else if (reasoncode.equals("CGE")) { + } else if (reasoncode.equals("SGE")) { discountAmount = (hallDetails.getFullDayRent() * hallDetails.getCGEdiscount()) / 100; // hallAmount = hallDetails.getFullDayRent(); hallAmount = governmentevents.getFulldayhallamount(); @@ -1048,30 +1120,48 @@ public class BookingServiceImpl implements BookingService { if (reasonMaster != null) { List reasonDocMaster = reasonMaster.getReasonDocumentMasterList(); - List uploadedDocs = new ArrayList<>(); for (ReasonDocumentMaster rm : reasonDocMaster) { BookingDocuments bd = new BookingDocuments(); bd.setBookingDetails(bookingDetails); + boolean hasContent = false; + if (rm.isAddTextField()) { - bd.setName(formData.get(rm.getFieldName()).toString()); - bd.setBooking_label(rm.getFieldName()); + Object textFieldValue = formData.get(rm.getFieldName()); + if (textFieldValue != null && !textFieldValue.toString().isEmpty()) { + bd.setName(textFieldValue.toString()); + bd.setBooking_label(rm.getFieldName()); + hasContent = true; + } } + 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.setDocumentName(file.getOriginalFilename()); - bd.setDocumentType(file.getContentType()); + if (file != null && !file.isEmpty()) { + 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()); + + // Ensure directory exists + File dir = new File(uploadDirectory + "/" + reasonMaster.getReason()); + if (!dir.exists()) { + dir.mkdirs(); + } - try (FileOutputStream fos = new FileOutputStream(filePath)) { - byte[] bytes = file.getBytes(); - fos.write(bytes); - } catch (Exception e) { - throw new RuntimeException(e); + try (FileOutputStream fos = new FileOutputStream(filePath)) { + byte[] bytes = file.getBytes(); + fos.write(bytes); + hasContent = true; + } catch (Exception e) { + throw new RuntimeException(e); + } } + } + + if (hasContent) { bookingDocumentsRepository.save(bd); uploadedDocs.add(bd); } @@ -1080,6 +1170,12 @@ public class BookingServiceImpl implements BookingService { } } + if (bookingDetails != null) { + String refId = getBookingRefIdByBookingId(bookingDetails.getBookingId()); + hs.put("bookingRefId", refId); + } + + hs.put("uploadedDocs", uploadedDocs); return hs; } @@ -3009,4 +3105,238 @@ public class BookingServiceImpl implements BookingService { return bookingDetailsRepository.getCounterWiseBookingList(fromDate, toDate); } + @Override + public String saveHallRequestDetails(String fromDate, String toDate, int startingSlot, int endingSlot, + String relationship, String reason, int hallId, int userId, + String orgType, String eventDesc, String offAddress, MultipartFile bonafide) { + + String exMsg = "Slot occupied"; + + HallDetails hallDetails = hallDetailService.getHallById(hallId); + Users user = userService.getUserById(userId); + + HallRequestDetails hallRequestDetails = new HallRequestDetails(); + hallRequestDetails.setStartDate(fromDate); + hallRequestDetails.setEndDate(toDate); + hallRequestDetails.setStartingSlot(startingSlot); + hallRequestDetails.setEndingSlot(endingSlot); + hallRequestDetails.setReason(reason); + hallRequestDetails.setHallId(hallId); + hallRequestDetails.setUserId(userId); + hallRequestDetails.setOrgType(orgType); + hallRequestDetails.setEventDescription(eventDesc); + hallRequestDetails.setOfficeDetails(offAddress); + if (bonafide != null && !bonafide.isEmpty()) { + hallRequestDetails.setBonafidePath(serverPath + "images/" + bonafide.getOriginalFilename()); + String filePath = uploadDirectory + "/" + bonafide.getOriginalFilename(); + // File saving logic is missing here in original method, but NCP is fixed. + } else { + hallRequestDetails.setBonafidePath(null); + } + hallRequestDetailsRepository.save(hallRequestDetails); + + BookingDetails bookingDetails = new BookingDetails(); + bookingDetails.setBookingDate(LocalDate.now()); + bookingDetails.setBookingStatus(BookingStatus.PENDING); + bookingDetails.setBookingtype(BookingDetails.BookingType.ONLINE); + bookingDetails.setEndDate(toDate); + bookingDetails.setStartDate(fromDate); + bookingDetails.setStartingSlot(startingSlot); + bookingDetails.setEndingSlot(endingSlot); + bookingDetails.setReason(reason); + bookingDetails.setNoOfDays(1); + bookingDetails.setRefundStatus(RefundStatus.WAITING); + bookingDetails.setScheduleCount(0); + bookingDetails.setRelationship(relationship); + bookingDetails.setComments("Booking Slot not Confirmed."); + bookingDetails.setUsers(user); + bookingDetails.setHallDetails(hallDetails); + BookingDetails SavedBookingDetails = bookingDetailsRepository.save(bookingDetails); + int bookingId = SavedBookingDetails.getBookingId(); + + // BookingCalendar bookingCalendar = new BookingCalendar(); + // bookingCalendar.setBookingDetails(bookingDetails); + // bookingCalendar.setBookingDate(LocalDate.parse(fromDate)); + // bookingCalendar.setStartingSlot(startingSlot); + // bookingCalendar.setEndingSlot(endingSlot); + // bookingCalendar.setHallDetails(hallDetails); + // bookingCalendar.setUsers(user); + // bookingCalendarRepository.save(bookingCalendar); + + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + LocalDate startDate = LocalDate.parse(fromDate, formatter); + LocalDate endDate = LocalDate.parse(toDate, formatter); + + int i = 0; + + for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) { + BookingCalendar bookingCalendar = bookingCalendarRepository.findByBdateAndHallId(date, hallId); + + if (bookingCalendar != null) { + 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"); + throw new RuntimeException(exMsg); + } else if (bookingCalendar.isMorningSlot() && bookingCalendar.isEveningSlot()) { + // 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) ); + throw new RuntimeException(exMsg); + } 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) ); + throw new RuntimeException(exMsg); + } + + } else { + String uniqueId = date.format(DateTimeFormatter.ofPattern("yyyyMMdd")) + hallId; + System.out.println("uniqueId....." + uniqueId); + + bookingCalendar = new BookingCalendar(); + bookingCalendar.setBdate(date); + bookingCalendar.setHallId(hallId); + bookingCalendar.setIs_booked(0); + bookingCalendar.setIs_active(true); + bookingCalendar.setUnique_id(uniqueId); + } + + // Mark the appropriate slot as booked based on starting and ending slots + if (date.equals(startDate)) { + // System.out.println(i + "start :-"+bookingCalendar.toString()); + + if (bookingDetails.getStartingSlot() == 1) { + bookingCalendar.setMorningSlot(true); + bookingCalendar.setBookingId_1(String.valueOf(bookingId)); + bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1); + if (!date.equals(endDate)) { + 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) { + bookingCalendar.setEveningSlot(true); + bookingCalendar.setBookingId_2(String.valueOf(bookingId)); + bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1); + } + + } else { + bookingCalendar.setEveningSlot(true); + bookingCalendar.setBookingId_2(String.valueOf(bookingId)); + bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1); + } + } else if (date.equals(endDate)) { + if (bookingDetails.getEndingSlot() == 1) { + bookingCalendar.setMorningSlot(true); + bookingCalendar.setBookingId_1(String.valueOf(bookingId)); + bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1); + } else { + bookingCalendar.setEveningSlot(true); + bookingCalendar.setBookingId_2(String.valueOf(bookingId)); + bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1); + if (bookingDetails.getEndingSlot() == 2) { + bookingCalendar.setMorningSlot(true); + bookingCalendar.setBookingId_1(String.valueOf(bookingId)); + bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1); + } + } + } else { + // For dates between start and end date, mark both slots as booked + bookingCalendar.setMorningSlot(true); + bookingCalendar.setEveningSlot(true); + bookingCalendar.setBookingId_1(String.valueOf(bookingId)); + bookingCalendar.setBookingId_2(String.valueOf(bookingId)); + bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 2); + } + // System.out.println(i + "end:-"+bookingCalendar.toString()); + bookingCalendarRepository.save(bookingCalendar); + i++; + } + + bookingDetailsRepository.save(bookingDetails); + + return "success"; + + } + + @Override + public List getPendingGovtRequests() { + return hallRequestDetailsRepository.findPendingRequests(); + } + + @Override + public List getApprovedGovtRequests() { + return hallRequestDetailsRepository.findApprovedRequests(); + } + + @Override + public List getRejectedGovtRequests() { + return hallRequestDetailsRepository.findRejectedRequests(); + } + + @Override + @Transactional + public void updateGovtRequest(int reqId, String action, double discountPercentage, boolean nocRequired) { + HallRequestDetails request = hallRequestDetailsRepository.findById(reqId) + .orElseThrow(() -> new RuntimeException("Request not found")); + BookingDetails booking = bookingDetailsRepository.findById(request.getBookingId()) + .orElseThrow(() -> new RuntimeException("Booking not found")); + + if ("ACCEPT".equalsIgnoreCase(action)) { + if (nocRequired) { + request.setBookingStatus("WAITING_FOR_NOC"); + booking.setBookingStatus(BookingStatus.WAITING_FOR_NOC); + } else { + request.setBookingStatus("APPROVED"); + booking.setBookingStatus(BookingStatus.APPROVED); + } + + // Apply discount + if (discountPercentage > 0) { + float discountFactor = (float) (1 - (discountPercentage / 100)); + booking.setHallAmount(booking.getHallAmount() * discountFactor); + booking.setDepositAmount(booking.getDepositAmount() * discountFactor); + booking.setGst(booking.getGst() * discountFactor); + } + + } else if ("REJECT".equalsIgnoreCase(action)) { + request.setBookingStatus("REJECTED"); + booking.setBookingStatus(BookingStatus.REJECTED); + } + + hallRequestDetailsRepository.save(request); + bookingDetailsRepository.save(booking); + } + + @Override + public List> getvphcollectionpending(int bookingId) { + + return bookingDetailsRepository.findApprovedBookingWithHallRequest(bookingId); + } + + public boolean isPaymentAlreadyDoneOrInitiated(int bookingId) { + + boolean existsInPayments = paymentsRepository.existsByBookingDetails_BookingId(bookingId); + + boolean existsInTransaction = transactionResponseRepository.existsByBookingId(bookingId); + + return existsInPayments || existsInTransaction; + } + } diff --git a/src/main/java/com/gcc/communityHall/service/Impl/ReasonMasterImpl.java b/src/main/java/com/gcc/communityHall/service/Impl/ReasonMasterImpl.java index 9d3ff7e..a9f9b36 100644 --- a/src/main/java/com/gcc/communityHall/service/Impl/ReasonMasterImpl.java +++ b/src/main/java/com/gcc/communityHall/service/Impl/ReasonMasterImpl.java @@ -26,45 +26,45 @@ public class ReasonMasterImpl implements ReasonMasterService { @Autowired ReasonDocMasterRepository reasonDocMasterRepository; - + @Autowired private WebConfig webConfig; - + @Autowired private ApplicationLogsRepository applicationLogsRepository; - + @Autowired private HttpSession session; @Override public String saveTheReason(ReasonMaster reasonMaster) { - List reasonDocumentMasterList =reasonMaster.getReasonDocumentMasterList(); + List reasonDocumentMasterList = reasonMaster.getReasonDocumentMasterList(); reasonMaster.setReasonDocumentMasterList(null); - ReasonMaster resMaster =reasonMasterRepository.save(reasonMaster); + ReasonMaster resMaster = reasonMasterRepository.save(reasonMaster); webConfig.addResourceHandlers(webConfig.registryHandler); - if(reasonDocumentMasterList!=null) { + if (reasonDocumentMasterList != null) { for (ReasonDocumentMaster reasonDocMaster : reasonDocumentMasterList) { reasonDocMaster.setReasonMaster(resMaster); reasonDocMasterRepository.save(reasonDocMaster); } } - String adminname = (String) session.getAttribute("usertype"); - Integer loginid = (Integer) session.getAttribute("id"); - ApplicationLogs logs=new ApplicationLogs(); - logs.setComments("Action by " + adminname); - logs.setLoginId(loginid); - logs.setLogType("Reasons:-"+reasonMaster.getReason()); - InetAddress inetAddress; - try { - inetAddress = InetAddress.getLocalHost(); - String hostname = InetAddress.getLocalHost().getHostName(); - logs.setIpaddress(inetAddress.getHostAddress()); - logs.setSystemName(hostname); - } catch (UnknownHostException e) { - e.printStackTrace(); - } - applicationLogsRepository.save(logs); + String adminname = (String) session.getAttribute("usertype"); + Integer loginid = (Integer) session.getAttribute("id"); + ApplicationLogs logs = new ApplicationLogs(); + logs.setComments("Action by " + adminname); + logs.setLoginId(loginid); + logs.setLogType("Reasons:-" + reasonMaster.getReason()); + InetAddress inetAddress; + try { + inetAddress = InetAddress.getLocalHost(); + String hostname = InetAddress.getLocalHost().getHostName(); + logs.setIpaddress(inetAddress.getHostAddress()); + logs.setSystemName(hostname); + } catch (UnknownHostException e) { + e.printStackTrace(); + } + applicationLogsRepository.save(logs); return "Success"; } @@ -73,17 +73,24 @@ public class ReasonMasterImpl implements ReasonMasterService { return reasonMasterRepository.findById(reasonId).get(); } - @Override - public List getAllReasons() { - return reasonMasterRepository.findAll(); - } - @Override - public List getReasonDocumentDetailsByReasonId(int reasonId) { - return reasonDocMasterRepository.findByReasonMasterReasonId(reasonId); - } - - @Override + @Override + public List getAllReasons() { + return reasonMasterRepository.findAll(); + } + + @Override + public List getReasonDocumentDetailsByReasonId(int reasonId) { + return reasonDocMasterRepository.findByReasonMasterReasonId(reasonId); + } + + @Override public ReasonMaster getReasonByName(String reasonName) { return reasonMasterRepository.findByReason(reasonName); } + + @Override + public List getAllReasonsWithStatus() { + return reasonMasterRepository.getAllReasonsWithStatus(); + + } } diff --git a/src/main/java/com/gcc/communityHall/service/ReasonMasterService.java b/src/main/java/com/gcc/communityHall/service/ReasonMasterService.java index 1d55223..dcf8483 100644 --- a/src/main/java/com/gcc/communityHall/service/ReasonMasterService.java +++ b/src/main/java/com/gcc/communityHall/service/ReasonMasterService.java @@ -7,9 +7,15 @@ import com.gcc.communityHall.entity.ReasonMaster; public interface ReasonMasterService { - String saveTheReason(ReasonMaster reasonMaster); - ReasonMaster getReasonById(int reasonId); + String saveTheReason(ReasonMaster reasonMaster); + + ReasonMaster getReasonById(int reasonId); + List getAllReasons(); + List getReasonDocumentDetailsByReasonId(int reasonId); + ReasonMaster getReasonByName(String reasonName); + + List getAllReasonsWithStatus(); } diff --git a/src/main/resources/templates/user/hallbookingform.html b/src/main/resources/templates/user/hallbookingform.html index a434c28..7e70f8b 100644 --- a/src/main/resources/templates/user/hallbookingform.html +++ b/src/main/resources/templates/user/hallbookingform.html @@ -2188,7 +2188,7 @@ // $("#rentamount_td").html(response.rentAmount); $("#actualhallAmount_td").html(response.actualhallamount); // $("#hallAmount_td").html(response.netAmount); - $("#gst_td").html(response.gstAmount); + $("#gst_td").html(response.gst); $("#depositAmount_td").html(response.depositAmount); // $("#discount_td").html(response.discount + "%"); $("#totalAmount_td").html(response.totalAmount); @@ -3194,7 +3194,7 @@ } let minDays = parseInt(document.getElementById("mindays").value, 10); - let maxDays = parseInt(document.getElementById("maxdays").value, 10); + let maxDays = parseInt(document.getElementById("maxdays").value, 10); const serverDate = new Date($("#serverDate").val() + "T00:00:00");