diff --git a/.classpath b/.classpath index d91be04b..2d9bac5e 100644 --- a/.classpath +++ b/.classpath @@ -39,17 +39,11 @@ - - - - - - diff --git a/.gitignore b/.gitignore index c2187eec..422e7586 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ target/classes/ target/classes/application-dev.properties target/classes/application-prod.properties +/communityHallDocuments_test diff --git a/jwtToken.txt b/jwtToken.txt index 944441b6..9014d974 100644 --- a/jwtToken.txt +++ b/jwtToken.txt @@ -1 +1 @@ -eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyVHlwZSI6ImhlYWRxdWFydGVycyIsImhhbGxJZCI6MywiaGFsbElkcyI6IjMiLCJtb2JpbGVOdW1iZXIiOjEyMzQ1Njc4OTEsImVtcGxveWVlSWQiOiI2Iiwiem9uZSI6IjAwIiwiZXhwIjoxNzgxNTA2NDEwfQ.GsMmYYsPT_S2rsgB_q1hFaX-2uu3Z1HvKwijAbA1Ck5ruG9Q2JaV_ZGZGic-Jl0LLRUPHi5Xs_6jCvfg6UbiNA \ No newline at end of file +eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyVHlwZSI6ImhlYWRxdWFydGVycyIsImhhbGxJZCI6MCwiaGFsbElkcyI6IiIsIm1vYmlsZU51bWJlciI6OTUxNzUzODUyNCwiem9uZSI6IjAwIiwiZXhwIjoxNzgzOTI4NDY4fQ.JDuWljfRXzemAjgmLj4MFq3DgmL9Z1hbE8_LoLpQQ0jLZp4wBbyvmEopk9BHmWtzh8SlDN6dxQHEJDsxTRt0_Q \ No newline at end of file diff --git a/src/main/java/com/gcc/communityHall/controller/AdminAPIController.java b/src/main/java/com/gcc/communityHall/controller/AdminAPIController.java index 02c703a8..946aea7c 100644 --- a/src/main/java/com/gcc/communityHall/controller/AdminAPIController.java +++ b/src/main/java/com/gcc/communityHall/controller/AdminAPIController.java @@ -543,16 +543,8 @@ public class AdminAPIController { @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 ); - List blockedBookings = bookingService.getBlockedEvents(fromDate, toDate, hallIds); - - // List bookingDetails = - // bookingService.getByBookingId(fromDate,toDate,hallIds,blockingId,bookingId); + public ResponseEntity> getBlockedEvents() { + List blockedBookings = bookingService.getBlockedEvents(); if (blockedBookings.isEmpty()) { // System.out.println("No blocked bookings found."); @@ -579,50 +571,69 @@ public class AdminAPIController { return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Blocking ID not found."); } - // Get the booking IDs from the blocking date entity + // Get the booking IDs from the blocking date entity (may be null/empty for + // block-only entries) String bookingIds = blockingDate.getBookingIds(); String hallIds = blockingDate.getHallId(); - // Convert the booking IDs to a list of integers - List bookingIdList = Arrays.stream(bookingIds.split(",")) - .map(Integer::parseInt) - .collect(Collectors.toList()); + // Parse booking IDs only if present + List bookingIdList = (bookingIds != null && !bookingIds.trim().isEmpty()) + ? Arrays.stream(bookingIds.split(",")) + .map(String::trim) + .filter(s -> !s.isEmpty()) + .map(Integer::parseInt) + .collect(Collectors.toList()) + : Collections.emptyList(); // Convert the hall IDs to a list of longs if provided - List hallIdList = hallIds != null ? Arrays.stream(hallIds.split(",")) - .map(Long::parseLong) - .collect(Collectors.toList()) + List hallIdList = (hallIds != null && !hallIds.trim().isEmpty()) + ? Arrays.stream(hallIds.split(",")) + .map(Long::parseLong) + .collect(Collectors.toList()) : Collections.emptyList(); // Fetch the booking calendar entries within the date range 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."); - } - - // Iterate over bookingCalendars and update them as needed + // ── Smart unblock: per-slot decision ────────────────────────────────── + // If morning+evening+is_blocked are all true AND an APPROVED user booking + // exists for that hall/date → only clear is_blocked (leave slots intact). + // Otherwise (GCC-owned slot) → clear everything. for (BookingCalendar bookingslots : bookingCalendars) { - bookingslots.setBookingId_1(null); - bookingslots.setBookingId_2(null); - bookingslots.setMorningSlot(false); - bookingslots.setEveningSlot(false); - bookingslots.setIs_blocked(false); + if (bookingslots.isMorningSlot() && bookingslots.isEveningSlot() && bookingslots.getIs_blocked()) { + List approvedBookings = bookingDetailsRepository.findByHallIdAndDate( + bookingslots.getBdate(), bookingslots.getHallId()); + if (!approvedBookings.isEmpty()) { + // Approved user booking owns the slots — only remove gcc flag + bookingslots.setIs_blocked(false); + } else { + // GCC owned this slot fully — release everything + bookingslots.setBookingId_1(null); + bookingslots.setBookingId_2(null); + bookingslots.setMorningSlot(false); + bookingslots.setEveningSlot(false); + bookingslots.setIs_blocked(false); + } + } else { + // Partial slot scenario — only clear the gcc overlay flag + bookingslots.setIs_blocked(false); + } bookingCalendarRepository.save(bookingslots); } blockingDate.setBlockedStatus(GccBlockingDate.BlockedStatus.UNBLOCKED); blockingDateRepository.save(blockingDate); - // Process each bookingId and update the booking details + // Update GCC_BLOCKED booking_details entries back to GCC_UNBLOCKED for (int bookingId : bookingIdList) { Optional bookingDetails = bookingDetailsRepo.findById(bookingId); if (bookingDetails.isPresent()) { BookingDetails bookings = bookingDetails.get(); - bookings.setBookingStatus(BookingDetails.BookingStatus.GCC_UNBLOCKED); - bookings.setRefundStatus(BookingDetails.RefundStatus.NA); - bookingDetailsRepo.save(bookings); + if (bookings.getBookingStatus() == BookingDetails.BookingStatus.GCC_BLOCKED) { + bookings.setBookingStatus(BookingDetails.BookingStatus.GCC_UNBLOCKED); + bookings.setRefundStatus(BookingDetails.RefundStatus.NA); + bookingDetailsRepo.save(bookings); + } } } String adminname = (String) session.getAttribute("usertype"); @@ -755,6 +766,44 @@ public class AdminAPIController { return hallService.getHallImages(hallId); } + @Operation(summary = "GCC Block Without Cancelling REST API", description = "REST API to Block halls without cancelling existing bookings (smart slot logic)") + @PostMapping("/blockWithoutCancel") + public ResponseEntity blockWithoutCancel( + @RequestParam("fromDate") String fromDate, + @RequestParam("toDate") String toDate, + @RequestParam("hallID") String hallID, + @RequestParam("reasonforblocking") String reasonforblocking, + @RequestParam(value = "description", required = false) String[] descriptions, + @RequestParam(value = "document", required = false) MultipartFile[] documents, + HttpSession session) { + + String updatedBy = (String) session.getAttribute("employeeId"); + List hallIdsList = Arrays.stream(hallID.split(",")) + .map(Long::parseLong) + .collect(Collectors.toList()); + + bookingService.blockWithoutCancellingBookings(fromDate, toDate, hallIdsList, reasonforblocking, + updatedBy, descriptions, documents); + + 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("Gcc Block Without Cancel for the Reason:-" + reasonforblocking); + 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 ResponseEntity.ok("Success"); + } + @Operation(summary = "GCC Blocking REST API", description = "REST API to Block the Halls by Admin") // GccBlocking Api @PostMapping("/cancelAll") diff --git a/src/main/java/com/gcc/communityHall/controller/Admincontroller.java b/src/main/java/com/gcc/communityHall/controller/Admincontroller.java index 355ae670..045ff91c 100644 --- a/src/main/java/com/gcc/communityHall/controller/Admincontroller.java +++ b/src/main/java/com/gcc/communityHall/controller/Admincontroller.java @@ -30,6 +30,7 @@ import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; import org.springframework.web.multipart.MultipartFile; @@ -43,6 +44,8 @@ import com.gcc.communityHall.entity.HallDetails; import com.gcc.communityHall.entity.Notification; import com.gcc.communityHall.entity.Settlement; import com.gcc.communityHall.entity.Users; +import com.gcc.communityHall.entity.Login; +import com.gcc.communityHall.entity.LoginHallId; import com.gcc.communityHall.others.UserSession; import com.gcc.communityHall.paymentService.entity.TransactionResponse; import com.gcc.communityHall.paymentService.repository.TransactionResponseRepository; @@ -54,12 +57,15 @@ import com.gcc.communityHall.repository.HallDetailsRepository; import com.gcc.communityHall.repository.NotificationRepository; import com.gcc.communityHall.repository.SettlementRepository; import com.gcc.communityHall.repository.UsersRepository; +import com.gcc.communityHall.repository.LoginHallIdRepository; +import com.gcc.communityHall.repository.LoginRepository; import com.gcc.communityHall.service.BookingService; import com.gcc.communityHall.service.HallDetailService; import com.gcc.communityHall.service.ReasonMasterService; import com.gcc.communityHall.service.UserService; import jakarta.servlet.http.HttpSession; +import jakarta.transaction.Transactional; @Controller @RequestMapping("/communityhall/admin") @@ -110,6 +116,12 @@ public class Admincontroller { @Autowired private TransactionResponseRepository transactionResponseRepository; + @Autowired + private LoginRepository loginRepository; + + @Autowired + private LoginHallIdRepository loginHallIdRepository; + @GetMapping("/dashboard") public String viewDashboard( @RequestParam(required = false, defaultValue = "all zones") String zone, @@ -120,7 +132,7 @@ public class Admincontroller { // Validate JWT token if (token != null && jwtUtil.validateToken(token)) { - //System.out.println("tokennnnnnnnnnnnnnns"+token); + // System.out.println("tokennnnnnnnnnnnnnns"+token); // Token is valid, proceed with dashboard logic String adminName = (String) session.getAttribute("usertype"); long mobileno = (long) session.getAttribute("mobileno"); @@ -147,7 +159,6 @@ public class Admincontroller { } } - @GetMapping("/Reports") public String viewReports(Model model, HttpSession session) { String adminname = (String) session.getAttribute("usertype"); @@ -174,7 +185,6 @@ public class Admincontroller { } } - @GetMapping("/HallDetails") public String viewHallDetails(Model model, HttpSession session) { String adminname = (String) session.getAttribute("usertype"); @@ -263,9 +273,9 @@ public class Admincontroller { List cancelledbookings = bookingDetailsRepository.findAllSettlementCancelledList(); List rejectedbookings = bookingDetailsRepository.findAllSettlementRejectedList(); model.addAttribute("settlementlist", settlement); - //AKI + // AKI List settlementIntiated = bookingDetailsRepository.findSettlementInitiatedPending(); - model.addAttribute("settlementIntiated", settlementIntiated); + model.addAttribute("settlementIntiated", settlementIntiated); model.addAttribute("cancelledbookings", cancelledbookings); model.addAttribute("rejectedbookings", rejectedbookings); System.out.println("Settlement List: " + settlement); @@ -287,8 +297,10 @@ public class Admincontroller { String zone = (String) session.getAttribute("zone"); model.addAttribute("zone", zone); List settlementrefundfailed = bookingDetailsRepository.findAllSettlementRefundFailed(); - List refundfailedcancelledbookings = bookingDetailsRepository.findAllRefundFaileCancelledList(); - List refundfailedrejectedbookings = bookingDetailsRepository.findAllRefundFaileRejectedList(); + List refundfailedcancelledbookings = bookingDetailsRepository + .findAllRefundFaileCancelledList(); + List refundfailedrejectedbookings = bookingDetailsRepository + .findAllRefundFaileRejectedList(); model.addAttribute("settlementrefundfailed", settlementrefundfailed); model.addAttribute("refundfailedcancelledbookings", refundfailedcancelledbookings); model.addAttribute("refundfailedrejectedbookings", refundfailedrejectedbookings); @@ -392,6 +404,20 @@ public class Admincontroller { } } + // ── New enhanced GCC Blocking page (does NOT affect the existing page) ── + @GetMapping("/GccblockingNew") + public String viewGccBlockingNew(Model model, HttpSession session) { + String adminname = (String) session.getAttribute("usertype"); + if (adminname != null) { + long mobileno = (long) session.getAttribute("mobileno"); + model.addAttribute("mobileno", mobileno); + model.addAttribute("adminname", adminname); + return "admin/gccblocking-new"; + } else { + session.invalidate(); + return "redirect:/communityhall/login"; + } + } // Utility method to ensure distinct by a key private static Predicate distinctByKey(Function keyExtractor) { @@ -410,7 +436,7 @@ public class Admincontroller { @RequestParam float hallArea, @RequestParam String ebNumber, @RequestParam float ebCostPerUnit, - @RequestParam int parkingCapacity, + @RequestParam String parkingCapacity, @RequestParam int seatingCapacity, @RequestParam String doorNo, @RequestParam String street, @@ -426,8 +452,10 @@ public class Admincontroller { @RequestParam long hallInchargeNo, @RequestParam("hallImages") MultipartFile[] hallImages, HttpSession session) { String updatedId = (String) session.getAttribute("employeeId"); - hallDetailService.saveHall(hallName, depositAmount, halfDayAmt, fullDayAmt, gst, hallArea, ebNumber, ebCostPerUnit, parkingCapacity, seatingCapacity, doorNo, - street, area, zone, division, landMark, city, pinCode, latitude, longitude, hallInchargeName, hallInchargeNo, updatedId, hallImages, halfdepositAmt); + hallDetailService.saveHallByAdmin(hallName, depositAmount, halfDayAmt, fullDayAmt, gst, hallArea, ebNumber, + ebCostPerUnit, parkingCapacity, seatingCapacity, doorNo, + street, area, zone, division, landMark, city, pinCode, latitude, longitude, hallInchargeName, + hallInchargeNo, updatedId, hallImages, halfdepositAmt); String adminname = (String) session.getAttribute("usertype"); Integer loginid = (Integer) session.getAttribute("id"); ApplicationLogs logs = new ApplicationLogs(); @@ -444,7 +472,8 @@ public class Admincontroller { e.printStackTrace(); } applicationLogsRepository.save(logs); - // Redirect to a success page or return a ModelAndView as per your application flow + // Redirect to a success page or return a ModelAndView as per your application + // flow return "redirect:/communityhall/admin/halldetailslist"; } @@ -558,48 +587,60 @@ public class Admincontroller { @PostMapping("/getReport") public String generateReport(Model model, - @RequestParam(name = "FromDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) String fromDate, - @RequestParam(name = "ToDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) String toDate, - @RequestParam(name = "request") String request, - @RequestParam(name = "userstatus", required = false) String userstatus, - @RequestParam(name = "usertype", required = false) String usertype, - @RequestParam(name = "bookingStatus", required = false) String bookingStatus, - @RequestParam(name = "refundStatus", required = false) String refundStatus, - @RequestParam(name = "paymentStatus", required = false) String paymentStatus, - @RequestParam(name = "filterby", required = false) String filterby, - @RequestParam(name = "zone1", required = false, defaultValue = "ALL") String zone, - @RequestParam(name = "division1", required = false, defaultValue = "ALL") String division, - @RequestParam(name = "hall1", required = false) Integer hallid, - @RequestParam(name = "basedon", required = false) String basedon, - @RequestParam(name = "bookingId", required = false) Long bookingId, - @RequestParam(name = "reporttype", required = false) String reporttype, - @RequestParam(name = "counterId", required = false) String counterId, HttpSession session) throws JsonProcessingException { + @RequestParam(name = "FromDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) String fromDate, + @RequestParam(name = "ToDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) String toDate, + @RequestParam(name = "request") String request, + @RequestParam(name = "userstatus", required = false) String userstatus, + @RequestParam(name = "usertype", required = false) String usertype, + @RequestParam(name = "bookingStatus", required = false) String bookingStatus, + @RequestParam(name = "refundStatus", required = false) String refundStatus, + @RequestParam(name = "paymentStatus", required = false) String paymentStatus, + @RequestParam(name = "filterby", required = false) String filterby, + @RequestParam(name = "zone1", required = false, defaultValue = "ALL") String zone, + @RequestParam(name = "division1", required = false, defaultValue = "ALL") String division, + @RequestParam(name = "hall1", required = false) Integer hallid, + @RequestParam(name = "basedon", required = false) String basedon, + @RequestParam(name = "bookingId", required = false) Long bookingId, + @RequestParam(name = "reporttype", required = false) String reporttype, + @RequestParam(name = "counterId", required = false) String counterId, HttpSession session) + throws JsonProcessingException { String adminname = (String) session.getAttribute("usertype"); if (adminname != null) { long mobileno = (long) session.getAttribute("mobileno"); model.addAttribute("mobileno", mobileno); List userList = handleUserRequest(request, fromDate, toDate, userstatus, usertype); - List bookingList = handleBookingRequest(request, fromDate, toDate, bookingStatus, filterby, bookingId, zone, division, hallid); - List bookingSettlementList = handleBookingSettlementRequest(request, fromDate, toDate, refundStatus, filterby); - //List paymentList = request.equals("3") ? bookingService.getAllPaymentsDetails(fromDate, toDate,zone,division,hallid) : new ArrayList<>(); + List bookingList = handleBookingRequest(request, fromDate, toDate, bookingStatus, filterby, + bookingId, zone, division, hallid); + List bookingSettlementList = handleBookingSettlementRequest(request, fromDate, toDate, + refundStatus, filterby); + // List paymentList = request.equals("3") ? + // bookingService.getAllPaymentsDetails(fromDate, toDate,zone,division,hallid) : + // new ArrayList<>(); List paymentList = new ArrayList<>(); List extrapaymentList = new ArrayList<>(); if (request.equals("3")) { if (paymentStatus == null || paymentStatus.isEmpty()) { paymentList = bookingService.getAllPaymentsDetails(fromDate, toDate, null, zone, division, hallid); } else { - paymentList = bookingService.getAllPaymentsDetails(fromDate, toDate, paymentStatus, zone, division, hallid); + paymentList = bookingService.getAllPaymentsDetails(fromDate, toDate, paymentStatus, zone, division, + hallid); } } if (request.equals("8")) { if (paymentStatus == null || paymentStatus.isEmpty()) { - extrapaymentList = bookingService.getAllExtraPaymentsDetails(fromDate, toDate, null, zone, division, hallid); + extrapaymentList = bookingService.getAllExtraPaymentsDetails(fromDate, toDate, null, zone, division, + hallid); } else { - extrapaymentList = bookingService.getAllExtraPaymentsDetails(fromDate, toDate, paymentStatus, zone, division, hallid); + extrapaymentList = bookingService.getAllExtraPaymentsDetails(fromDate, toDate, paymentStatus, zone, + division, hallid); } } - List userbookingList = request.equals("4") ? bookingService.getBookingUserDetailsReport(fromDate, toDate) : new ArrayList<>(); - //List hallbookingList = request.equals("5") ? bookingService.getBookingHallDetailsReport(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<>(); // In your controller method // Fetch booking count by zone List totalcount = new ArrayList<>(); @@ -609,13 +650,13 @@ public class Admincontroller { totalcount = bookingDetailsRepository.countBookingsByZone(); // Format zone data totalcount = totalcount.stream() - .map(data -> new Object[]{"Zone-" + data[0], data[1]}) + .map(data -> new Object[] { "Zone-" + data[0], data[1] }) .collect(Collectors.toList()); } else if ("division".equals(basedon)) { totalcount = bookingDetailsRepository.countBookingsByDivisions(); // Format division data totalcount = totalcount.stream() - .map(data -> new Object[]{"Division-" + data[0], data[1]}) + .map(data -> new Object[] { "Division-" + data[0], data[1] }) .collect(Collectors.toList()); } @@ -626,22 +667,24 @@ public class Admincontroller { model.addAttribute("basedon", basedon); model.addAttribute("totalcount", totalcount); model.addAttribute("totalBookings", totalBookings); - List hallbookingList = handleBookingHallDetailsReportRequest(request, fromDate, toDate, filterby, zone, division, hallid); + List hallbookingList = handleBookingHallDetailsReportRequest(request, fromDate, toDate, filterby, + zone, division, hallid); if ("9".equals(request)) { - if("abstract".equals(reporttype)){ + if ("abstract".equals(reporttype)) { List counterBookingList = new ArrayList<>(); counterBookingList = bookingService.getCounterWiseBookingCount(fromDate, toDate); model.addAttribute("counterBookingList", counterBookingList); System.out.println("counterBookingList.." + counterBookingList); - List hallBookingByCounter = bookingService.getHallWiseBookingDetails(fromDate, toDate, counterId); + List hallBookingByCounter = bookingService.getHallWiseBookingDetails(fromDate, toDate, + counterId); // Convert to JSON for JS usage String hallBookingJson = new ObjectMapper().writeValueAsString(hallBookingByCounter); model.addAttribute("hallBookingJson", hallBookingJson); - - List hallBookingDetails = bookingService.getBookingDetailsForAllHalls(fromDate, toDate, counterId, hallid); + List hallBookingDetails = bookingService.getBookingDetailsForAllHalls(fromDate, toDate, + counterId, hallid); String hallBookingDetailsJson = new ObjectMapper().writeValueAsString(hallBookingDetails); model.addAttribute("hallBookingDetailsJson", hallBookingDetailsJson); @@ -669,15 +712,15 @@ public class Admincontroller { String counterWiseBookingJson = new ObjectMapper().writeValueAsString(counterWiseBookingList); model.addAttribute("counterWiseBookingList", counterWiseBookingJson); } - //ak + // ak if ("11".equals(request)) { - // Fetch Settlement Initiated Report details - List settlementInitiatedList = bookingService.getSettlementInitiatedReport(fromDate, toDate); - System.out.println("settlementInitatedList"+ settlementInitiatedList); + // Fetch Settlement Initiated Report details + List settlementInitiatedList = bookingService.getSettlementInitiatedReport(fromDate, toDate); + System.out.println("settlementInitatedList" + settlementInitiatedList); - // Add the list to the model - model.addAttribute("settlementInitiatedList", settlementInitiatedList); -} + // Add the list to the model + model.addAttribute("settlementInitiatedList", settlementInitiatedList); + } model.addAttribute("filterby", filterby); model.addAttribute("users", userList); @@ -701,7 +744,6 @@ public class Admincontroller { model.addAttribute("hall1", hallid); model.addAttribute("adminname", adminname); System.out.println("request" + request); - return "admin/reports"; } else { @@ -710,7 +752,8 @@ public class Admincontroller { } } - private List handleBookingHallDetailsReportRequest(String request, String fromDate, String toDate, String filterby, String zone, String division, Integer hallid) { + private List handleBookingHallDetailsReportRequest(String request, String fromDate, String toDate, + String filterby, String zone, String division, Integer hallid) { if (!request.equals("5")) { return new ArrayList<>(); } @@ -731,7 +774,8 @@ public class Admincontroller { return new ArrayList<>(); } - 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<>(); } @@ -747,8 +791,8 @@ public class Admincontroller { return userService.getAllUsers(fromDate, toDate); } - - private List handleBookingRequest(String request, String fromDate, String toDate, String bookingStatus, String filterby, Long bookingId, String zone, String division, Integer hallid) { + private List handleBookingRequest(String request, String fromDate, String toDate, String bookingStatus, + String filterby, Long bookingId, String zone, String division, Integer hallid) { if (!request.equals("2")) { return new ArrayList<>(); } @@ -759,10 +803,12 @@ public class Admincontroller { return bookingDetailsRepo.getAllBookingDetailsWithBookingId(fromDate, toDate, bookingId); } if (bookingId != null && !bookingStatus.isEmpty()) { - return bookingDetailsRepo.getAllBookingDetailsWithBookingIdwithbookingStatus(fromDate, toDate, bookingId, bookingStatus); + return bookingDetailsRepo.getAllBookingDetailsWithBookingIdwithbookingStatus(fromDate, toDate, bookingId, + bookingStatus); } if (bookingId == null && filterby.isEmpty() && !bookingStatus.isEmpty()) { - return bookingService.getBookingDetailsByBookingDateWithStatus(fromDate, toDate, bookingStatus, zone, division, hallid); + return bookingService.getBookingDetailsByBookingDateWithStatus(fromDate, toDate, bookingStatus, zone, + division, hallid); } if (!filterby.isEmpty()) { @@ -770,7 +816,8 @@ public class Admincontroller { if (bookingStatus.isEmpty()) { return bookingService.getBookingDetailsByBookingDate(fromDate, toDate, zone, division, hallid); } else { - return bookingService.getBookingDetailsByBookingDateWithStatus(fromDate, toDate, bookingStatus, zone, division, hallid); + return bookingService.getBookingDetailsByBookingDateWithStatus(fromDate, toDate, bookingStatus, + zone, division, hallid); } } @@ -778,7 +825,8 @@ public class Admincontroller { if (bookingStatus.isEmpty()) { return bookingService.getBookingDetailsByEventDate(fromDate, toDate, zone, division, hallid); } else { - return bookingService.getBookingDetailsByEventDateWithStatus(fromDate, toDate, bookingStatus, zone, division, hallid); + return bookingService.getBookingDetailsByEventDateWithStatus(fromDate, toDate, bookingStatus, zone, + division, hallid); } } @@ -787,8 +835,8 @@ public class Admincontroller { return new ArrayList<>(); } - - private List handleBookingSettlementRequest(String request, String fromDate, String toDate, String refundStatus, String filterby) { + private List handleBookingSettlementRequest(String request, String fromDate, String toDate, + String refundStatus, String filterby) { if (!request.equals("6")) { return new ArrayList<>(); } @@ -804,7 +852,8 @@ public class Admincontroller { if (refundStatus.isEmpty()) { return bookingService.getAllBookingsettlementDetailsByBookingDate(fromDate, toDate); } else { - return bookingService.getAllBookingsettlementDetailsByBookingDateWithStatus(fromDate, toDate, refundStatus); + return bookingService.getAllBookingsettlementDetailsByBookingDateWithStatus(fromDate, toDate, + refundStatus); } } @@ -812,7 +861,8 @@ public class Admincontroller { if (refundStatus.isEmpty()) { return bookingService.getAllBookingsettlementDetailsByEventDate(fromDate, toDate); } else { - return bookingService.getAllBookingsettlementDetailsByEventDateWithStatus(fromDate, toDate, refundStatus); + return bookingService.getAllBookingsettlementDetailsByEventDateWithStatus(fromDate, toDate, + refundStatus); } } @@ -888,28 +938,28 @@ public class Admincontroller { } } - // @GetMapping("/getDeveloperdetails") -// public String getDetails(Model model,HttpSession session) -// { -// String adminname = (String) session.getAttribute("usertype"); -// if(adminname != null) { -// long mobileno = (long) session.getAttribute("mobileno"); -// model.addAttribute("mobileno", mobileno); -// return "admin/developer"; -// }else { -// session.invalidate(); // Invalidate the session to clear all session attributes -// return "redirect:/communityhall/login"; -// } -// } + // @GetMapping("/getDeveloperdetails") + // public String getDetails(Model model,HttpSession session) + // { + // String adminname = (String) session.getAttribute("usertype"); + // if(adminname != null) { + // long mobileno = (long) session.getAttribute("mobileno"); + // model.addAttribute("mobileno", mobileno); + // return "admin/developer"; + // }else { + // session.invalidate(); // Invalidate the session to clear all session + // attributes + // return "redirect:/communityhall/login"; + // } + // } @PostMapping("/getDeveloperdetails") public String generatedetails(Model model, - @RequestParam(name = "FromDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) String fromDate, - @RequestParam(name = "ToDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) String toDate, - @RequestParam(name = "request") String request, - @RequestParam(name = "bookingId", required = false) Long bookingId, - @RequestParam(name = "hallId", required = false) Long hallId, - @RequestParam(name = "hallName", required = false) String hallName, HttpSession session) { - + @RequestParam(name = "FromDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) String fromDate, + @RequestParam(name = "ToDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) String toDate, + @RequestParam(name = "request") String request, + @RequestParam(name = "bookingId", required = false) Long bookingId, + @RequestParam(name = "hallId", required = false) Long hallId, + @RequestParam(name = "hallName", required = false) String hallName, HttpSession session) { String adminname = (String) session.getAttribute("usertype"); if (adminname != null) { @@ -938,15 +988,17 @@ public class Admincontroller { List BookingCalendar = new ArrayList<>(); if (request.equals("3")) { System.out.println("outside"); -// if (hallName.isEmpty()) { -// System.out.println("check1"); -// // Fetch all details for the given date range -// BookingCalendar = bookingService.getBookingCalendarDetails(fromDate, toDate,hallName); -// } else { -// System.out.println("check2"); -// // Fetch filtered details based on hallName -// BookingCalendar = bookingService.getBookingCalendarDetails(fromDate, toDate, hallName); -// } + // if (hallName.isEmpty()) { + // System.out.println("check1"); + // // Fetch all details for the given date range + // BookingCalendar = bookingService.getBookingCalendarDetails(fromDate, + // toDate,hallName); + // } else { + // System.out.println("check2"); + // // Fetch filtered details based on hallName + // BookingCalendar = bookingService.getBookingCalendarDetails(fromDate, toDate, + // hallName); + // } BookingCalendar = bookingService.getBookingCalendarDetails(fromDate, toDate, bookingId, hallName); } @@ -1045,7 +1097,6 @@ public class Admincontroller { } } - @GetMapping("/logout") public String viewLogout(Model model, HttpSession session) { session.invalidate(); @@ -1072,5 +1123,255 @@ public class Admincontroller { } } -} + // care taker, counter and officer login creation added by kanimozhi 15062026 + @GetMapping("/login-creation") + public String viewLoginCreation(Model model, HttpSession session) { + String adminname = (String) session.getAttribute("usertype"); + if (adminname != null && "admin".equals(adminname)) { + long mobileno = (long) session.getAttribute("mobileno"); + model.addAttribute("mobileno", mobileno); + model.addAttribute("adminname", adminname); + + // Fetch existing active non-admin logins (returns projection, not full entity) + List> loginList = loginRepository.findActiveLogins(); + model.addAttribute("loginList", loginList); + + // Fetch hall details for the modal dropdown + List> hallList = hallDetailsRepo.getAllHalls(); + model.addAttribute("hallList", hallList); + + return "admin/login-creation"; + } else { + session.invalidate(); + return "redirect:/communityhall/login"; + } + } + + @PostMapping("/login-creation/save") + @ResponseBody + @Transactional + public Map saveLoginCreation( + @RequestParam("mobileNumber") long mobileNumber, + @RequestParam("name") String name, + @RequestParam("password") String password, + @RequestParam("userType") String userType, + @RequestParam("zone") String zone, + @RequestParam(value = "hallIds", required = false) List hallIds, + HttpSession session) { + + Map response = new HashMap<>(); + String adminname = (String) session.getAttribute("usertype"); + if (adminname == null && "admin".equals(adminname)) { + response.put("status", "error"); + response.put("message", "Session expired. Please log in again."); + return response; + } + try { + /* -------- Duplicate hall check for counter / caretaker -------- */ + boolean isSingleMode = "counter".equals(userType) || "caretaker".equals(userType); + boolean isMulitpleMode = "officer".equals(userType); + if (isSingleMode && hallIds != null && !hallIds.isEmpty()) { + int hallId = hallIds.get(0); + int existingCount = loginRepository.countActiveLoginsByHallId(hallId, userType); + if (existingCount > 0) { + // Fetch hall name for a clear message + String hallName = hallId + ""; + try { + String fetched = hallDetailsRepo.findHallNameById(hallId); + if (fetched != null && !fetched.isBlank()) + hallName = fetched; + } catch (Exception ignored) { + } + response.put("status", "error"); + response.put("message", "A login already exists for hall \"" + hallName + + "\". Only one counter/caretaker login is allowed per hall."); + return response; + } + } + + /* -------- Duplicate hall check for officer -------- */ + if (isMulitpleMode && hallIds != null && !hallIds.isEmpty()) { + int existingCount = loginRepository.getActiveLoginsByHallIds(hallIds, userType); + if (existingCount > 0) { + response.put("status", "error"); + response.put("message", + "A login already exists for the selected hall(s). Only one officer login is allowed per hall."); + return response; + } + } + + Login login = new Login(); + login.setMobileNumber(mobileNumber); + login.setName(name); + login.setPassword(password); + login.setUserType(userType); + login.setZone(zone); + login.setActive(true); + login.setDelete(false); + + if (hallIds == null || hallIds.isEmpty()) { + // HQ may have no hall assigned + loginRepository.save(login); + } else if (hallIds.size() == 1) { + // Single hall: store directly in login.hallId + login.setHallId(hallIds.get(0)); + loginRepository.save(login); + } else { + // Multiple halls: store first in hallId, rest in login_hall_ids + login.setHallId(hallIds.get(0)); + Login savedLogin = loginRepository.save(login); + for (int hallId : hallIds) { + LoginHallId loginHallId = new LoginHallId(savedLogin, hallId); + loginHallIdRepository.save(loginHallId); + } + } + + response.put("status", "success"); + response.put("message", "Login created successfully."); + } catch (Exception e) { + response.put("status", "error"); + response.put("message", "Error creating login: " + e.getMessage()); + } + return response; + } + + @PostMapping("/login-creation/delete/{id}") + @ResponseBody + @Transactional + public Map deleteLogin(@PathVariable("id") int id, HttpSession session) { + Map response = new HashMap<>(); + String adminname = (String) session.getAttribute("usertype"); + if (adminname == null && "admin".equals(adminname)) { + response.put("status", "error"); + response.put("message", "Session expired. Please log in again."); + return response; + } + try { + Login login = loginRepository.findLoginById(id); + if (login == null) { + response.put("status", "error"); + response.put("message", "Login not found."); + return response; + } + // Soft delete: set is_active = 0, is_delete = 1 + login.setActive(false); + login.setDelete(true); + loginRepository.save(login); + + // Also soft-delete any related login_hall_ids + loginHallIdRepository.softDeleteByLoginId(id); + + response.put("status", "success"); + response.put("message", "Login deleted successfully."); + } catch (Exception e) { + response.put("status", "error"); + response.put("message", "Error deleting login: " + e.getMessage()); + } + return response; + } + + @GetMapping("/login-creation/check-mobile") + @ResponseBody + public Map checkMobileExists(@RequestParam("mobileNumber") long mobileNumber, HttpSession session) { + Map response = new HashMap<>(); + try { + int count = loginRepository.countByMobileNumber(mobileNumber); + response.put("exists", count > 0); + } catch (Exception e) { + response.put("exists", false); + response.put("error", e.getMessage()); + } + return response; + } + + @GetMapping("/login-creation/halls-by-zone") + @ResponseBody + public List> getHallsByZone(@RequestParam("zone") String zone, HttpSession session) { + try { + return hallDetailsRepo.getHallsByZone(zone); + } catch (Exception e) { + return new java.util.ArrayList<>(); + } + } + + @GetMapping("/login-creation/get-login-halls") + @ResponseBody + public Map getLoginHalls(@RequestParam("loginId") int loginId, HttpSession session) { + Map response = new HashMap<>(); + try { + Login login = loginRepository.findLoginById(loginId); + if (login == null) { + response.put("status", "error"); + response.put("message", "Login not found."); + return response; + } + // Collect all assigned hall IDs + java.util.List assignedHallIds = new java.util.ArrayList<>(); + if (login.getHallId() != 0) { + assignedHallIds.add(login.getHallId()); + } + loginHallIdRepository.findActiveByLoginId(loginId).forEach(lh -> assignedHallIds.add(lh.getHallId())); + + response.put("status", "success"); + response.put("loginId", loginId); + response.put("name", login.getName()); + response.put("zone", login.getZone()); + response.put("userType", login.getUserType()); + response.put("assignedHallIds", assignedHallIds); + // Also return all halls for the zone + response.put("hallsForZone", hallDetailsRepo.getHallsByZone(login.getZone())); + } catch (Exception e) { + response.put("status", "error"); + response.put("message", "Error fetching login halls: " + e.getMessage()); + } + return response; + } + + @PostMapping("/login-creation/update-halls") + @ResponseBody + @Transactional + public Map updateLoginHalls( + @RequestParam("loginId") int loginId, + @RequestParam("hallIds") java.util.List hallIds, + HttpSession session) { + Map response = new HashMap<>(); + try { + Login login = loginRepository.findLoginById(loginId); + if (login == null) { + response.put("status", "error"); + response.put("message", "Login not found."); + return response; + } + if (hallIds == null || hallIds.isEmpty()) { + response.put("status", "error"); + response.put("message", "At least one hall must be selected."); + return response; + } + + // Clear all existing login_hall_ids rows for this login + loginHallIdRepository.softDeleteByLoginId(loginId); + + if (hallIds.size() == 1) { + // Single hall: store in login.hall_id only + login.setHallId(hallIds.get(0)); + loginRepository.save(login); + } else { + // Multiple halls: first goes to login.hall_id, rest to login_hall_ids + login.setHallId(hallIds.get(0)); + loginRepository.save(login); + for (int i = 1; i < hallIds.size(); i++) { + LoginHallId lh = new LoginHallId(login, hallIds.get(i)); + loginHallIdRepository.save(lh); + } + } + response.put("status", "success"); + response.put("message", "Hall assignment updated successfully."); + } catch (Exception e) { + response.put("status", "error"); + response.put("message", "Error updating halls: " + e.getMessage()); + } + return response; + } + +} diff --git a/src/main/java/com/gcc/communityHall/controller/HQAPIController.java b/src/main/java/com/gcc/communityHall/controller/HQAPIController.java new file mode 100644 index 00000000..c780e854 --- /dev/null +++ b/src/main/java/com/gcc/communityHall/controller/HQAPIController.java @@ -0,0 +1,1502 @@ +package com.gcc.communityHall.controller; + +import java.io.IOException; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.ui.Model; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; +import org.springframework.web.multipart.MultipartFile; + +import com.gcc.communityHall.component.JwtUtil; +import com.gcc.communityHall.dto.BookingResponseDTO; +import com.gcc.communityHall.dto.ErrorResponseDto; +import com.gcc.communityHall.entity.ApplicationLogs; +import com.gcc.communityHall.entity.BookingCalendar; +import com.gcc.communityHall.entity.BookingDetails; +import com.gcc.communityHall.entity.BookingDetails.BookingStatus; +import com.gcc.communityHall.entity.BookingDetails.RefundStatus; +import com.gcc.communityHall.entity.DiscountRange; +import com.gcc.communityHall.entity.FloorDetails; +import com.gcc.communityHall.entity.GccBlockingDate; +import com.gcc.communityHall.entity.GccBlockingHistory; +import com.gcc.communityHall.entity.HallDetails; +import com.gcc.communityHall.entity.HallImages; +import com.gcc.communityHall.entity.Notification; +import com.gcc.communityHall.entity.ReasonDocumentMaster; +import com.gcc.communityHall.entity.ReasonMaster; +import com.gcc.communityHall.entity.Settlement; +import com.gcc.communityHall.entity.Users; +import com.gcc.communityHall.others.AppConfig; +import com.gcc.communityHall.others.UserSession; +import com.gcc.communityHall.paymentService.service.PaymentGatewayServiceImpl; +import com.gcc.communityHall.repository.ApplicationLogsRepository; +import com.gcc.communityHall.repository.BookingCalendarRepository; +import com.gcc.communityHall.repository.BookingDetailsRepository; +import com.gcc.communityHall.repository.DiscountRangeRepository; +import com.gcc.communityHall.repository.GccBlockingDateRepository; +import com.gcc.communityHall.repository.GccBlockingHistoryRepository; +import com.gcc.communityHall.repository.HallDetailsRepository; +import com.gcc.communityHall.repository.HallReasonRestrictionRepository; +import com.gcc.communityHall.repository.HallImagesRepository; +import com.gcc.communityHall.repository.NotificationRepository; +import com.gcc.communityHall.repository.ReasonMasterRepository; +import com.gcc.communityHall.repository.SettlementRepository; +import com.gcc.communityHall.repository.UsersRepository; +import com.gcc.communityHall.service.BookingService; +import com.gcc.communityHall.service.HallDetailService; +import com.gcc.communityHall.service.ReasonMasterService; +import com.gcc.communityHall.service.SettlementService; +import com.gcc.communityHall.service.UserService; +import com.gcc.communityHall.service.Impl.BookingServiceImpl; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import io.swagger.v3.oas.annotations.tags.Tag; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.media.ExampleObject; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; +import lombok.AllArgsConstructor; + +//@RestController +//@RequestMapping("/admin/api") +@Tag(name = "CRUD REST APIs for HQ's in CommunityHall", description = "CRUD REST APIs in CommunityHall to CREATE, UPDATE, FETCH AND DELETE Booking details") +@RestController +@RequestMapping("/communityhall/headquarters/api") +@AllArgsConstructor +@Validated +public class HQAPIController { + + @Autowired + private HallDetailsRepository hallDetailsRepository; + + @Autowired + private HallDetailService hallDetailService; + @Autowired + private BookingDetailsRepository bookingDetailsRepository; + + @Autowired + private SettlementService settlementService; + + @Autowired + private SettlementRepository settlementRepository; + + @Autowired + private BookingServiceImpl bookingService; + + @Autowired + private BookingDetailsRepository bookingDetailsRepo; + + @Autowired + private DiscountRangeRepository discountRangeRepo; + + @Autowired + private GccBlockingDateRepository blockingDateRepository; + + @Autowired + private ReasonMasterService reasonMasterService; + + @Autowired + private HallDetailService hallService; + @Autowired + private UserService userService; + + @Autowired + private BookingCalendarRepository bookingCalendarRepository; + + @Autowired + private UsersRepository userRepository; + + @Autowired + private HallImagesRepository hallImagesRepository; + + @Autowired + private JwtUtil jwtUtil; + + @Autowired + private AppConfig appConfig; + + @Autowired + private PaymentGatewayServiceImpl paymentGatewayServiceImpl; + + @Autowired + private NotificationRepository notificationRepo; + + @Autowired + private HttpSession session; + + @Autowired + private ApplicationLogsRepository applicationLogsRepository; + + @Autowired + private HallReasonRestrictionRepository hallReasonRestrictionRepository; + + @Operation(summary = "Update HallDetails REST API", description = "REST API to update the Hall Details") + @ApiResponses({ + @ApiResponse(responseCode = "200", description = "HTTP Status UPDATED", content = @Content(mediaType = "text/plain", schema = @Schema(implementation = HallDetails.class), examples = @ExampleObject(value = "Hall details updated successfully"))), + @ApiResponse(responseCode = "500", description = "HTTP Status Internal Server Error", content = @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponseDto.class), examples = @ExampleObject(name = "Internal Server Error Example", value = "{ \"path\": \"/updateHallDetails\", \"status\": 500, \"error\": \"Internal Server Error\", \"timestamp\": \"2024-06-22T05:47:04.347+00:00\" }"))) + }) + @PostMapping("/updateHallDetails") + public ResponseEntity updateHallInfo( + @RequestParam("hallId") String hallId, + @RequestParam("zone") String zone, + @RequestParam("division") String division, + @RequestParam("hallName") String hallName, + @RequestParam("doorNo") String doorNo, + @RequestParam("street") String street, + @RequestParam("area") String area, + @RequestParam("pinCode") int pinCode, + @RequestParam("landMark") String landMark, + @RequestParam("latitude") String latitude, + @RequestParam("longitude") String longitude, + @RequestParam("hallInchargeMobno") long hallInchargeMobno, + @RequestParam("hallInchargeName") String hallInchargeName, + @RequestParam("depositAmount") float depositAmount, + @RequestParam("halfDepositAmount") float halfDepositAmount, + @RequestParam("fullDayRent") float fullDayRent, + @RequestParam("halfDayRent") float halfDayRent, + @RequestParam("parkingCapacity") String parkingCapacity, + @RequestParam("seatingCapacity") int seatingCapacity, + @RequestParam(value = "images", required = false) List images, + @RequestParam("ebNumber") String ebNumber, + @RequestParam("ebCostPerUnit") float ebCostPerUnit, + @RequestParam("gst") float gst, + @RequestParam("city") String city, + @RequestParam("isActive") boolean isActive, + @RequestParam(value = "floorName", required = false) List floorNames, + @RequestParam(value = "floorCapacity", required = false) List floorCapacities) { + + HallDetails hallDetails = new HallDetails(); + hallDetails.setHallId(Integer.parseInt(hallId)); + hallDetails.setZone(zone); + hallDetails.setDivision(division); + hallDetails.setHallName(hallName); + hallDetails.setDoorNo(doorNo); + hallDetails.setStreet(street); + hallDetails.setArea(area); + hallDetails.setPinCode(pinCode); + hallDetails.setLandMark(landMark); + hallDetails.setLatitude(latitude); + hallDetails.setLongitude(longitude); + hallDetails.setHallInchargeMobno(hallInchargeMobno); + hallDetails.setHallInchargeName(hallInchargeName); + hallDetails.setDepositAmount(depositAmount); + hallDetails.setHalfDepositAmount(halfDepositAmount); + hallDetails.setFullDayRent(fullDayRent); + hallDetails.setHalfDayRent(halfDayRent); + hallDetails.setParkingCapacity(parkingCapacity); + hallDetails.setSeatingCapacity(seatingCapacity); + hallDetails.setEbNumber(ebNumber); + hallDetails.setEbCostPerUnit(ebCostPerUnit); + hallDetails.setGst(gst); + hallDetails.setCity(city); + hallDetails.setActive(isActive); + + hallDetailService.updateHallDetail(hallDetails, images); + + // Update floor details for this hall (HQ only addition) + hallDetailService.updateFloorDetails(Integer.parseInt(hallId), floorNames, floorCapacities); + + 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("Hall Details edit:-" + hallName); + 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 ResponseEntity.ok("Success"); + } + + @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\" }"))) + }) + @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); + 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("Settlement Initiation:-" + status); + 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 (updateInitialiseSettlement != null) { + return new ResponseEntity<>(updateInitialiseSettlement, HttpStatus.OK); + } else { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + } + + @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") + }) + @GetMapping("/getHallDetails/{hallId}") + public ResponseEntity getHallDetails(@PathVariable String hallId) { + int id; + try { + id = Integer.parseInt(hallId); + } catch (NumberFormatException e) { + return ResponseEntity.badRequest().build(); + } + + HallDetails hallDetails = hallDetailsRepository.findHallDetailsById(id); + // System.out.println(hallDetails.isActive()); + if (hallDetails != null) { + return ResponseEntity.ok(hallDetails); + } else { + return ResponseEntity.notFound().build(); + } + } + + @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, + @RequestParam float discountRange, HttpSession session) { + + Optional existingDiscountRanges = discountRangeRepo.findByUsertype(userType); + if (!existingDiscountRanges.isEmpty()) { + return "waiting"; + } + + String adminname = (String) session.getAttribute("usertype"); + DiscountRange discount = new DiscountRange(); + discount.setUsertype(userType); + discount.setDiscountRange(discountRange); + discount.setcDate(LocalDate.now()); + discount.setUpdtedBy(adminname); + discount.setIs_active(true); + discount.setIs_delete(false); + + discountRangeRepo.save(discount); + return "success"; + } + + @PostMapping("/savenotification") + public String saveNotification( + @RequestParam String notification, HttpSession session) { + + String adminname = (String) session.getAttribute("usertype"); + Notification newnotification = new Notification(); + newnotification.setNotification_description(notification); + newnotification.setCdate(LocalDate.now()); + newnotification.setCreatedBY(adminname); + newnotification.setActive(true); + newnotification.setDelete(false); + notificationRepo.save(newnotification); + Integer loginid = (Integer) session.getAttribute("id"); + ApplicationLogs logs = new ApplicationLogs(); + logs.setComments("Action by " + adminname); + logs.setLoginId(loginid); + logs.setLogType("Added New Notification:-" + newnotification.getNotification_description()); + 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"; + } + + @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) { + String adminname = (String) session.getAttribute("usertype"); + Optional existingDiscount = discountRangeRepo.findById(id); + if (existingDiscount.isPresent()) { + DiscountRange updatediscount = existingDiscount.get(); + updatediscount.setDiscountRange(discountRange); + updatediscount.setUpdtedBy(adminname); + updatediscount.setcDate(LocalDate.now()); + discountRangeRepo.save(updatediscount); + Integer loginid = (Integer) session.getAttribute("id"); + ApplicationLogs logs = new ApplicationLogs(); + logs.setComments("Action by " + adminname); + logs.setLoginId(loginid); + logs.setLogType("Discount Details Update:-" + updatediscount.getUsertype()); + 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"; + } else { + return "error: Entry with ID " + id + " not found"; + } + } + + @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)) { + discountRangeRepo.deleteById(id); + 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("Discount Details Delete:-" + id); + 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 ResponseEntity.ok("DiscountRange with ID " + id + " deleted successfully."); + } else { + return ResponseEntity.notFound().build(); // Return 404 if the entry does not exist + } + } + + @PostMapping("/deletenotificationById/{id}") + public ResponseEntity deleteNotificationById(@PathVariable int id, HttpSession session) { + Optional notification = notificationRepo.findById(id); + Notification newnotification = notification.get(); + newnotification.setActive(false); + newnotification.setDelete(true); + String adminname = (String) session.getAttribute("usertype"); + newnotification.setUpdatedBy(adminname); + String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")); + newnotification.setUpdatedDate(date); + notificationRepo.save(newnotification); + Integer loginid = (Integer) session.getAttribute("id"); + ApplicationLogs logs = new ApplicationLogs(); + logs.setComments("Action by " + adminname); + logs.setLoginId(loginid); + logs.setLogType("Detele Notification:-" + newnotification.getNotification_description()); + 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 ResponseEntity.ok("Notification with ID " + id + " deleted successfully."); + + } + + @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 + @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 + @GetMapping("/getReasons") + @ResponseBody + public List getAllReasons() { + return reasonMasterService.getAllReasons(); + } + + // retrieving allowed reasons for a specific hall (filtered by restriction) + @GetMapping("/getAllowedReasons") + @ResponseBody + public List getAllowedReasons(@RequestParam int hallId) { + HallDetails hallDetails = hallDetailsRepository.findHallDetailsById(hallId); + if (hallDetails != null && hallDetails.isReasonRestricted()) { + List allowedReasonIds = hallReasonRestrictionRepository.findReasonIdsByHallId(hallId); + if (!allowedReasonIds.isEmpty()) { + List allReasons = reasonMasterService.getAllReasons(); + return allReasons.stream() + .filter(r -> allowedReasonIds.contains(r.getReasonId())) + .collect(java.util.stream.Collectors.toList()); + } + } + return reasonMasterService.getAllReasons(); + } + + @Operation(summary = "Reason Documents by reasonId REST API", description = "REST API to Get the ReasonDocuments By reasonId") + // Getting ReasonDocuments By reasonId + @GetMapping("/getReasonDocumentDetails") + public List getReasonDocumentDetails(@RequestParam int reasonId) { + return reasonMasterService.getReasonDocumentDetailsByReasonId(reasonId); + } + + @Operation(summary = "Booking Details by Fromdate,toDate and HallId REST API", description = "REST API to get the Booking Details by Fromdate,toDate and HallId for GccBlokcing") + // @GetMapping("/filter") + // public ResponseEntity> getFilteredBookings( + // @RequestParam("fromDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate + // fromDate, + // @RequestParam("toDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate + // toDate, + // @RequestParam("hallIds") List hallIds) { + // + // List bookings = bookingService.getFilteredBookings(fromDate, + // toDate, hallIds); + // + // List responses = new ArrayList<>(); + // for (BookingDetails bookingDetails : bookings) { + // // Fetch GccBlockingDate records for each bookingId + // List gccBlockedList = + // blockingDateRepository.getByBookingId(bookingDetails.getBookingId()); + // Integer blockingId = gccBlockedList.isEmpty() ? null : + // gccBlockedList.get(0).getBlockingId(); + // responses.add(new BookingResponseDTO(bookingDetails, blockingId)); + // } + // + // return ResponseEntity.ok(responses); + // } + @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 gccBlockedList = blockingDateRepository + .findByFromDateAndToDateBetweenAndHallIdIn(fromDate, toDate, hallIds); + + Map response = new HashMap<>(); + response.put("bookings", bookings); + response.put("blockedEvents", gccBlockedList); + + 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 + @GetMapping("/blockedevents") + public ResponseEntity> getBlockedEvents() { + List blockedBookings = bookingService.getBlockedEvents(); + if (blockedBookings.isEmpty()) { + return ResponseEntity.ok(blockedBookings); + } + + for (GccBlockingDate blockedBooking : blockedBookings) { + // System.out.println("Blocked Event: " + blockedBooking); + } + + return ResponseEntity.ok(blockedBookings); + } + + @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) { + + // Fetch the blocking date entity + GccBlockingDate blockingDate = blockingDateRepository.findById(blockingId).orElse(null); + + if (blockingDate == null) { + return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Blocking ID not found."); + } + + // Get the booking IDs from the blocking date entity + String bookingIds = blockingDate.getBookingIds(); + String hallIds = blockingDate.getHallId(); + + // Convert the booking IDs to a list of integers + List bookingIdList = Arrays.stream(bookingIds.split(",")) + .map(Integer::parseInt) + .collect(Collectors.toList()); + + // Convert the hall IDs to a list of longs if provided + List hallIdList = hallIds != null ? Arrays.stream(hallIds.split(",")) + .map(Long::parseLong) + .collect(Collectors.toList()) + : Collections.emptyList(); + + // Fetch the booking calendar entries within the date range + List bookingCalendars = bookingService.getBookedslots(fromDate, endDate, hallIdList); + + // ── Smart unblock: per-slot decision ────────────────────────────────── + // If morning+evening+is_blocked are all true AND an APPROVED user booking + // exists for that hall/date → only clear is_blocked (leave slots intact). + // Otherwise (GCC-owned slot) → clear everything. + for (BookingCalendar bookingslots : bookingCalendars) { + if (bookingslots.isMorningSlot() && bookingslots.isEveningSlot() && bookingslots.getIs_blocked()) { + List approvedBookings = bookingDetailsRepository.findByHallIdAndDate( + bookingslots.getBdate(), bookingslots.getHallId()); + if (!approvedBookings.isEmpty()) { + // Approved user booking owns the slots — only remove gcc flag + bookingslots.setIs_blocked(false); + } else { + // GCC owned this slot fully — release everything + bookingslots.setBookingId_1(null); + bookingslots.setBookingId_2(null); + bookingslots.setMorningSlot(false); + bookingslots.setEveningSlot(false); + bookingslots.setIs_blocked(false); + } + } else { + // Partial slot scenario — only clear the gcc overlay flag + bookingslots.setIs_blocked(false); + } + bookingCalendarRepository.save(bookingslots); + } + + blockingDate.setBlockedStatus(GccBlockingDate.BlockedStatus.UNBLOCKED); + blockingDateRepository.save(blockingDate); + + // Update GCC_BLOCKED booking_details entries back to GCC_UNBLOCKED + for (int bookingId : bookingIdList) { + Optional bookingDetails = bookingDetailsRepo.findById(bookingId); + if (bookingDetails.isPresent()) { + BookingDetails bookings = bookingDetails.get(); + if (bookings.getBookingStatus() == BookingDetails.BookingStatus.GCC_BLOCKED) { + bookings.setBookingStatus(BookingDetails.BookingStatus.GCC_UNBLOCKED); + bookings.setRefundStatus(BookingDetails.RefundStatus.NA); + bookingDetailsRepo.save(bookings); + } + } + } + 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("Gcc UnBlocking for the Id:-" + blockingDate.getBlockingId()); + 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 ResponseEntity.ok("Success"); + } + // @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) { + + // // Fetch the blocking date entity + // GccBlockingDate blockingDate = + // blockingDateRepository.findById(blockingId).orElse(null); + + // if (blockingDate == null) { + // return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Blocking ID not + // found."); + // } + + // // Get the booking IDs from the blocking date entity (may be null/empty for + // // block-only entries) + // String bookingIds = blockingDate.getBookingIds(); + // String hallIds = blockingDate.getHallId(); + + // // Parse booking IDs only if present + // List bookingIdList = (bookingIds != null && + // !bookingIds.trim().isEmpty()) + // ? Arrays.stream(bookingIds.split(",")) + // .map(String::trim) + // .filter(s -> !s.isEmpty()) + // .map(Integer::parseInt) + // .collect(Collectors.toList()) + // : Collections.emptyList(); + + // // Convert the hall IDs to a list of longs if provided + // List hallIdList = (hallIds != null && !hallIds.trim().isEmpty()) + // ? Arrays.stream(hallIds.split(",")) + // .map(Long::parseLong) + // .collect(Collectors.toList()) + // : Collections.emptyList(); + + // // Fetch the booking calendar entries within the date range + // List bookingCalendars = + // bookingService.getBookedslots(fromDate, endDate, hallIdList); + + // // Release the GCC block flag ONLY. + // // Do NOT touch bookingId_1, bookingId_2, morningSlot, or eveningSlot – + // // those belong to real user bookings that must remain intact. + // for (BookingCalendar bookingslots : bookingCalendars) { + // bookingslots.setIs_blocked(false); + // bookingCalendarRepository.save(bookingslots); + // } + + // blockingDate.setBlockedStatus(GccBlockingDate.BlockedStatus.UNBLOCKED); + // blockingDateRepository.save(blockingDate); + + // // Restore status of any bookings that were cancelled as part of this GCC + // block + // for (int bookingId : bookingIdList) { + // Optional bookingDetails = + // bookingDetailsRepo.findById(bookingId); + // if (bookingDetails.isPresent()) { + // BookingDetails bookings = bookingDetails.get(); + // bookings.setBookingStatus(BookingDetails.BookingStatus.GCC_UNBLOCKED); + // bookings.setRefundStatus(BookingDetails.RefundStatus.NA); + // bookingDetailsRepo.save(bookings); + // } + // } + // 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("Gcc UnBlocking for the Id:-" + + // blockingDate.getBlockingId()); + // 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 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 Block Without Cancelling REST API", description = "REST API to Block halls without cancelling existing bookings (smart slot logic)") + @PostMapping("/blockWithoutCancel") + public ResponseEntity blockWithoutCancel( + @RequestParam("fromDate") String fromDate, + @RequestParam("toDate") String toDate, + @RequestParam("hallID") String hallID, + @RequestParam("reasonforblocking") String reasonforblocking, + @RequestParam(value = "description", required = false) String[] descriptions, + @RequestParam(value = "document", required = false) MultipartFile[] documents, + HttpSession session) { + + String updatedBy = (String) session.getAttribute("employeeId"); + List hallIdsList = Arrays.stream(hallID.split(",")) + .map(Long::parseLong) + .collect(Collectors.toList()); + + bookingService.blockWithoutCancellingBookings(fromDate, toDate, hallIdsList, reasonforblocking, + updatedBy, descriptions, documents); + + 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("Gcc Block Without Cancel for the Reason:-" + reasonforblocking); + 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 ResponseEntity.ok("Success"); + } + + @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, + @RequestParam("toDate") String toDate, + @RequestParam("hallID") String hallID, + @RequestParam("reasonforblocking") String reasonforblocking, + @RequestParam(value = "selectedBookings", required = false) List selectedBookings, + @RequestParam(value = "description", required = false) String[] descriptions, // Handle descriptions + @RequestParam(value = "document", required = false) MultipartFile[] documents, // Handle documents + HttpSession session) { + + // Your existing logic + String updatedBy = (String) session.getAttribute("employeeId"); + + // Split and convert hall IDs + List hallIdsList = Arrays.stream(hallID.split(",")) + .map(Long::parseLong) + .collect(Collectors.toList()); + + System.out.println("fromDate " + fromDate + "\n toDate " + toDate + "\n hallID " + hallID + + "\n reasonforblocking " + reasonforblocking + "\n selectedBookings " + selectedBookings + + "\n descriptions " + descriptions + "\n documents " + documents + "\n updatedBy " + updatedBy); + + // Call the service with descriptions and 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(); + logs.setComments("Action by " + adminname); + logs.setLoginId(loginid); + logs.setLogType("Gcc Blocking for the Reason:-" + reasonforblocking); + 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 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) { + return bookingService.getAllBookingsByUserId(userId); + } + + @GetMapping("/settlement-approved") + public ResponseEntity> getApprovedSettlements(HttpSession session) { + 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); + // } + @GetMapping("/Gccblocking") + public ResponseEntity> getGccBlockingEvents(@RequestParam("hallId") String hallId) { + // System.out.println("Received hallId: " + hallId); + + List results = bookingService.getGccBlockingEvents(hallId); + + return ResponseEntity.ok(results); + } + + @GetMapping("/getblockedbookingdetails") + public ResponseEntity>> viewBlockedHallsByHallIdAndReason( + @RequestParam String hallIds, + @RequestParam int blockingId) { + + // System.out.println("Received hallIds: " + hallIds); + // System.out.println("Received blockingId: " + blockingId); + + List hallIdList; + try { + hallIdList = Arrays.stream(hallIds.split("\\s*,\\s*")) + .map(Integer::parseInt) + .collect(Collectors.toList()); + } catch (NumberFormatException e) { + System.err.println("Invalid hall ID format: " + e.getMessage()); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Collections.emptyList()); + } + + Optional gccOpt = blockingDateRepository.findById(blockingId); + if (!gccOpt.isPresent()) { + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Collections.emptyList()); + } + + GccBlockingDate savedGcc = gccOpt.get(); + LocalDate startDate = LocalDate.ofInstant(savedGcc.getStartDate().toInstant(), ZoneId.systemDefault()); + LocalDate endDate = LocalDate.ofInstant(savedGcc.getEndDate().toInstant(), ZoneId.systemDefault()); + + List> result = new ArrayList<>(); + + for (int hallId : hallIdList) { + int bookingCount = bookingDetailsRepository.countByHallIdAndBookingDateBetween(hallId, startDate, endDate); + // 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 + + Map hallInfo = new HashMap<>(); + hallInfo.put("hallName", hallDetails.getHallName()); + hallInfo.put("zone", hallDetails.getZone()); + hallInfo.put("division", hallDetails.getDivision()); + hallInfo.put("bookingCount", bookingCount); + hallInfo.put("bookingIds", bookingIds); + hallInfo.put("hallId", hallId); + + result.add(hallInfo); + } + } + + return ResponseEntity.ok(result); + } + + @GetMapping("/getbookingdetails") + public ResponseEntity> getBookingDetails(@RequestParam("bookingId") Long bookingId) { + // System.out.println("Received bookingId: " + bookingId); + try { + List details = bookingService.findBookingDetailsByBookingId(bookingId); + // System.out.println("bookingdetails==="+details); + return ResponseEntity.ok(details); + } catch (Exception e) { + e.printStackTrace(); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); + } + } + + @GetMapping("/blockedHallsByHallIdAndReason") + @ResponseBody + public Map viewBlockedHallsByHallIdAndReason( + @RequestParam String department, + @RequestParam String blockingReason, + @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); + + // Ensure distinct by hallId and other keys + List uniqueGccBlockingDates = blockedHalls.stream() + .filter(distinctByKey( + g -> Arrays.asList(g.getHallId(), g.getBlockingReason(), g.getStartDate(), g.getEndDate()))) + .collect(Collectors.toList()); + + // Prepare response data + Map response = new HashMap<>(); + if (!uniqueGccBlockingDates.isEmpty()) { + GccBlockingDate firstBlockedHall = uniqueGccBlockingDates.get(0); // Adjust as necessary + response.put("blockingReason", firstBlockedHall.getBlockingReason()); + response.put("cdate", firstBlockedHall.getCdate()); + response.put("startDate", firstBlockedHall.getStartDate()); + response.put("endDate", firstBlockedHall.getEndDate()); + + List> hallDetailsList = new ArrayList<>(); + for (GccBlockingDate blockedHall : uniqueGccBlockingDates) { + // Split the hallId string into individual hall IDs + String[] hallIds = blockedHall.getHallId().split(","); + + for (String hallIdStr : hallIds) { + try { + int hallId = Integer.parseInt(hallIdStr.trim()); + HallDetails hall = hallService.getHallById(hallId); + if (hall != null) { + Map hallDetails = new HashMap<>(); + hallDetails.put("hallName", hall.getHallName()); + hallDetails.put("zone", hall.getZone()); + hallDetails.put("division", hall.getDivision()); + hallDetails.put("numOfBookings", calculateBookings(hall, blockedHall)); + hallDetails.put("refundedAmount", calculateRefund(hall, blockedHall)); + hallDetailsList.add(hallDetails); + } + } catch (NumberFormatException e) { + // Handle the case where hallId is not a valid integer + e.printStackTrace(); + } + } + } + response.put("halls", hallDetailsList); + } else { + response.put("blockingReason", "N/A"); + response.put("cdate", "N/A"); + response.put("startDate", "N/A"); + response.put("endDate", "N/A"); + response.put("halls", Collections.emptyList()); + } + return response; + } + + // Utility method to ensure distinct by a key + private static Predicate distinctByKey(Function keyExtractor) { + Set seen = new HashSet<>(); + return t -> seen.add(keyExtractor.apply(t)); + } + + // Method to calculate number of bookings + private int calculateBookings(HallDetails hall, GccBlockingDate blockedHall) { + return blockingDateRepository.countBlockedBookings(hall.getHallId(), blockedHall.getStartDate(), + blockedHall.getEndDate()); + } + + private double calculateRefund(HallDetails hall, GccBlockingDate blockedHall) { + // Implement logic to calculate refund + return 0.0; + } + + // admin dashboard + @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, + @RequestParam(required = false, defaultValue = "ALL") String zone, + @RequestParam(required = false, defaultValue = "ALL") String division, + @RequestParam(required = false, defaultValue = "1000") Integer hallid, + @RequestParam(required = false, defaultValue = "ALL") String userType) { + + try { + 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 + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Collections.emptyMap()); + } + } + + @GetMapping("/getHallsDetailsByZone") + public ResponseEntity> getHallsDetailsByZone(@RequestParam String zone) { + Map hallzones = hallDetailService.getHallsDetailsByZone(zone); + // Debug log to verify the response before sending it to the client + // System.out.println("Response from getHallsDetailsByZone: " + hallzones); + return ResponseEntity.ok(hallzones); + } + + @GetMapping("/byhallid") + public ResponseEntity>> getBookingDetailsByHallId(@RequestParam int hallId) { + List> bookingDetails = bookingService.getBookingDetailsByHallId(hallId); + return ResponseEntity.ok(bookingDetails); + } + + @PostMapping("/savenewHallImages") + public ResponseEntity updateHallImages(@RequestParam("hallId") Integer hallId, + @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(); + // } + + @PutMapping("/updateHallImage/{hallImageId}") + public ResponseEntity> updateHallImage( + @PathVariable Integer hallImageId, + @RequestParam("hallImage") MultipartFile hallImage) throws IOException { + + try { + String newImageUrl = hallService.updateHallImage(hallImageId, hallImage); + Map response = new HashMap<>(); + response.put("newImageUrl", newImageUrl); + return ResponseEntity.ok(response); + } 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")); + } + } + + @DeleteMapping("/deleteHallImage/{hallImageId}") + public ResponseEntity deleteHallImage(@PathVariable Integer hallImageId) { + try { + // Find the image by ID and delete it + hallImagesRepository.deleteById(hallImageId); + return ResponseEntity.ok("Image deleted successfully."); + } catch (Exception e) { + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error deleting image."); + } + } + + @GetMapping("/bookingdetailsByzone") + public ResponseEntity> getBookingDetailsByZone(@RequestParam String zone) { + List bookingDetails = bookingDetailsRepository.findByZone(zone); + return ResponseEntity.ok(bookingDetails); + } + + @GetMapping("/divisionsByZone") + public List getDivisionsByZone(@RequestParam("zoneId") String zoneId) { + // Use zoneId instead of zone + return hallDetailsRepository.findDistinctDivisionsByZone(zoneId); + } + + // Fetch hall names by division + @GetMapping("/hallsByDivision") + public ResponseEntity> getHallsByDivision(@RequestParam String division) { + List halls = hallDetailsRepository.findHallsByDivision(division); + if (halls.isEmpty()) { + return new ResponseEntity<>(HttpStatus.NO_CONTENT); + } + return new ResponseEntity<>(halls, HttpStatus.OK); + } + + @PostMapping("/manualrefund") + public ResponseEntity manualRefund( + @RequestParam int bookingId, + @RequestParam String txansactionId, + @RequestParam int userId, + @RequestParam String code, + @RequestParam String amount) throws Exception { + + // Check if the code matches the value from AppConfig + if (code.equals(appConfig.getManualRefundCode())) { + // Call the refund method from PaymentService + String response = paymentGatewayServiceImpl.manualrefundTheAmount(bookingId, userId, txansactionId, amount); + // Check the response from the payment service + if ("Refunded".equals(response)) { + return ResponseEntity.ok("Refund processed successfully"); + } else { + // If there was an error in processing the refund + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error processing refund."); + } + } else { + // Return error message if the code doesn't match + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Code is wrong"); + } + } + + // gccapps + @GetMapping("/viewsettlement-pending") + public ResponseEntity> viewSettlementPendingMaster(HttpSession session) { + + List settlement = bookingDetailsRepository.findAllWithPendingRefundStatus(); + List cancelledbookings = bookingDetailsRepository.findPendingCancelledList(); + List rejectedbookings = bookingDetailsRepository.findPendingRejectedList(); + + Map response = new HashMap<>(); + response.put("settlementlist", settlement); + response.put("cancelledbookings", cancelledbookings); + response.put("rejectedbookings", rejectedbookings); + + return ResponseEntity.ok(response); + } + + @GetMapping("/viewsettlement-complete") + public ResponseEntity> viewSettlementcompleteMaster(HttpSession session) { + + List completedlist = bookingDetailsRepository.findAllwithCompletedRefundStatus(); + List Completedcancelledbookings = bookingDetailsRepository.findCompletedCancelledList(); + List Completedrejectedbookings = bookingDetailsRepository.findCompletedRejectedList(); + + Map response = new HashMap<>(); + response.put("completedlist", completedlist); + response.put("Completedcancelledbookings", Completedcancelledbookings); + response.put("Completedrejectedbookings", Completedrejectedbookings); + + return ResponseEntity.ok(response); + } + + @GetMapping("/viewsettlement-approved") + public ResponseEntity> viewSettlementApprovedMaster(HttpSession session) { + + List approvedSettlements = bookingDetailsRepository.findAllWithApprovedRefundStatus(); + List settlements = new ArrayList<>(approvedSettlements); + List approvedCancelledBookings = bookingDetailsRepository.findCancelledList(); + List approvedRejectedBookings = bookingDetailsRepository.findRejectedList(); + + Map response = new HashMap<>(); + response.put("settlementList", settlements); + response.put("approvedCancelledBookings", approvedCancelledBookings); + response.put("approvedRejectedBookings", approvedRejectedBookings); + + return ResponseEntity.ok(response); + } + + @GetMapping("/viewsettlement-reject") + public ResponseEntity> viewSettlementRejectedMaster(HttpSession session) { + + List settlementReject = bookingDetailsRepository.findSettlementRejected(); + + Map response = new HashMap<>(); + response.put("settlementlist", settlementReject); + + return ResponseEntity.ok(response); + } + + @GetMapping("/viewsettlement-initiated") + public ResponseEntity> viewSettlementInitiateMaster(HttpSession session) { + + List settlement = bookingDetailsRepository.findByBookingDetailsRefundStatus(); + List Initiatedcancelledbookings = bookingDetailsRepository.findInitiatedCancelledList(); + List Initiatedrejectedbookings = bookingDetailsRepository.findInitiatedRejectedList(); + + Map response = new HashMap<>(); + response.put("settlementlist", settlement); + response.put("Initiatedcancelledbookings", Initiatedcancelledbookings); + response.put("Initiatedrejectedbookings", Initiatedrejectedbookings); + + return ResponseEntity.ok(response); + } + + @GetMapping("/user-pending") + public ResponseEntity> viewApproval() { + List pendingList = userRepository.getPendingList(); + return new ResponseEntity<>(pendingList, HttpStatus.OK); + } + + @GetMapping("/user-approved") + public ResponseEntity> viewUserApproved() { + List approved = userRepository.getUserApproved(); + return new ResponseEntity<>(approved, HttpStatus.OK); + } + + @GetMapping("/user-reject") + public ResponseEntity> viewUserReject() { + List rejected = userRepository.getUserReject(); + return new ResponseEntity<>(rejected, HttpStatus.OK); + } + + @GetMapping("/halldetailslist") + public ResponseEntity> getHallDetailsList() { + List list = hallDetailsRepository.findAll(); + return ResponseEntity.ok(list); + } + + @GetMapping("/discountRange") + public ResponseEntity> getAllDiscountRanges() { + List discount = discountRangeRepo.findAll(); + return ResponseEntity.ok(discount); + } + + @PostMapping("/getReport") + public ResponseEntity> generateReport( + @RequestParam(name = "FromDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) String fromDate, + @RequestParam(name = "ToDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) String toDate, + @RequestParam(name = "request") String request, + @RequestParam(name = "userstatus", required = false) String userstatus, + @RequestParam(name = "usertype", required = false) String usertype, + @RequestParam(name = "bookingStatus", required = false) String bookingStatus, + @RequestParam(name = "refundStatus", required = false) String refundStatus, + @RequestParam(name = "bookingId", required = false) Long bookingId) { + + Map response = new HashMap<>(); + + 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<>(); + + response.put("users", userList); + response.put("bookings", bookingList); + response.put("fromdate", fromDate); + response.put("todate", toDate); + response.put("userstatus", userstatus); + response.put("bookingSettlementList", bookingSettlementList); + response.put("usertype", usertype); + response.put("bookingStatus", bookingStatus); + response.put("refundStatus", refundStatus); + response.put("request", request); + response.put("paymentLists", paymentList); + response.put("userbookingLists", userbookingList); + response.put("hallbookingLists", hallbookingList); + response.put("bookingId", bookingId); + + return new ResponseEntity<>(response, HttpStatus.OK); + } + + private List handleUserRequest(String request, String fromDate, String toDate, String userstatus, + String usertype) { + if (!request.equals("1")) { + return new ArrayList<>(); + } + if ((userstatus != null && !userstatus.isEmpty()) && (usertype != null && !usertype.isEmpty())) { + return userService.getAllUsersWithFilters(fromDate, toDate, userstatus, usertype); + } + if (userstatus.isEmpty() && (usertype != null && !usertype.isEmpty())) { + return userService.getAllUsersWithTypeFilters(fromDate, toDate, usertype); + } + if (usertype.isEmpty() && (userstatus != null && !userstatus.isEmpty())) { + return userService.getAllUsersWithStatusFilters(fromDate, toDate, userstatus); + } + return userService.getAllUsers(fromDate, toDate); + } + + private List handleBookingRequest(String request, String fromDate, String toDate, String bookingStatus, + Long bookingId) { + if (!request.equals("2")) { + return new ArrayList<>(); + } + if (bookingStatus != null && !bookingStatus.isEmpty()) { + return bookingDetailsRepo.getAllBookingDetailsWithStatus(fromDate, toDate, bookingStatus); + } else if (bookingId != null) { + return bookingDetailsRepo.getAllBookingDetailsWithBookingId(fromDate, toDate, bookingId); + } else { + return bookingDetailsRepo.getAllBookingDetails(fromDate, toDate); + } + } + + private List handleBookingSettlementRequest(String request, String fromDate, String toDate, + String refundStatus) { + if (!request.equals("6")) { + return new ArrayList<>(); + } + if (refundStatus != null && !refundStatus.isEmpty()) { + return bookingDetailsRepository.getAllBookingsettlementDetailsWithStatus(fromDate, toDate, refundStatus); + } + return bookingDetailsRepository.getAllBookingsettlementDetails(fromDate, toDate); + } + + @GetMapping("/getHallDetailsById") + public ResponseEntity>> getHallDetailsById(@RequestParam Integer hall_id) { + List> halldetails = bookingService.getHallDetailsForOfficer(hall_id); + return ResponseEntity.ok(halldetails); + } + + @GetMapping("/listgccblocking") + public ResponseEntity> getGccBlocking() { + + // Fetch all blocked GCC dates + List gccBlocked = blockingDateRepository.findAllBlocked(); + + // Ensure distinct by hallId, blockingReason, startDate, and endDate + List uniqueGccBlockingDates = gccBlocked.stream() + .filter(distinctByKey(g -> Arrays.asList( + g.getHallId(), + g.getBlockingReason(), + g.getStartDate(), + g.getEndDate()))) + .collect(Collectors.toList()); + + // Map to store the count of blocked halls for each GccBlockingDate + Map hallCountMap = new HashMap<>(); + for (GccBlockingDate blockedDate : uniqueGccBlockingDates) { + // Parse and count unique hall IDs + String hallIds = blockedDate.getHallId(); + if (hallIds != null && !hallIds.isEmpty()) { + Set uniqueHallIds = new HashSet<>(Arrays.asList(hallIds.split(","))); + int hallCount = uniqueHallIds.size(); + hallCountMap.put(blockedDate.getBlockingId(), hallCount); + } else { + hallCountMap.put(blockedDate.getBlockingId(), 0); // No halls blocked + } + } + + // Prepare the response data + Map response = new HashMap<>(); + response.put("gccblocked", uniqueGccBlockingDates); + response.put("hallCountMap", hallCountMap); + + return ResponseEntity.ok(response); + } + + @GetMapping("/details") + public ResponseEntity> getUserDetails( + @RequestParam("fromDate") String fromDate, + @RequestParam("toDate") String toDate) { + List userDetails = userRepository.findUserDetailsByBookingDate(fromDate, toDate); + return ResponseEntity.ok(userDetails); + } + + @GetMapping("/getPaymentswithRefunds") + public List getPaymentsWithRefunds(@RequestParam String startDate, @RequestParam String endDate) { + return userRepository.findPaymentsWithRefunds(startDate, endDate); + } + + @GetMapping("/getpaymentswithoutRefunds") + public List getPaymentsWithoutRefunds(@RequestParam String startDate, @RequestParam String endDate) { + return userRepository.findPaymentsWithoutRefunds(startDate, endDate); + } + + @GetMapping("/getRefundDetails") + public List getPaymentsWithRefundsOnly(@RequestParam String startDate, @RequestParam String endDate) { + return userRepository.findPaymentsWithRefundsOnly(startDate, endDate); + } + + @PostMapping("/send") + public ResponseEntity> sendMessage(@RequestBody Map messagePayload) { + String userMessage = messagePayload.get("message"); + + // Process the user message and prepare a response + String response = processMessage(userMessage); + + Map responseBody = new HashMap<>(); + responseBody.put("response", response); + + return ResponseEntity.ok(responseBody); + } + + private String processMessage(String userMessage) { + // Simple logic to return a response, could be more advanced (AI, NLP, etc.) + if (userMessage.toLowerCase().contains("hello")) { + return "Hello! How can I assist you today?"; + } else { + return "Thanks for your message! We will get back to you shortly."; + } + } + + @PostMapping("/uploadnoc") + public ResponseEntity uploadnoc(@RequestParam("nocFile") MultipartFile file, + @RequestParam("bookingid") int bookingId) { + try { + System.out.println("Received file: " + file.getOriginalFilename()); + System.out.println("Booking ID: " + bookingId); + + bookingService.uploadNOCFile(file, bookingId); + 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()); + } + } +} diff --git a/src/main/java/com/gcc/communityHall/controller/HeadquartersController.java b/src/main/java/com/gcc/communityHall/controller/HeadquartersController.java index e08047f1..3a24ef78 100644 --- a/src/main/java/com/gcc/communityHall/controller/HeadquartersController.java +++ b/src/main/java/com/gcc/communityHall/controller/HeadquartersController.java @@ -24,8 +24,10 @@ import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.multipart.MultipartFile; import com.gcc.communityHall.entity.BookingDetails; +import com.gcc.communityHall.entity.HallDetails; import com.gcc.communityHall.entity.Users; import com.gcc.communityHall.repository.BookingDetailsRepository; import com.gcc.communityHall.repository.HallDetailsRepository; @@ -735,6 +737,21 @@ public class HeadquartersController { } } + // ── New enhanced GCC Blocking page (does NOT affect the existing page) ── + @GetMapping("/GccblockingNew") + public String viewGccBlockingNew(Model model, HttpSession session) { + String headquartersname = (String) session.getAttribute("usertype"); + if (headquartersname != null && "headquarters".equals(headquartersname)) { + long mobileno = (long) session.getAttribute("mobileno"); + model.addAttribute("mobileno", mobileno); + model.addAttribute("headquartersname", headquartersname); + return "headquarters/gccblocking-new"; + } else { + session.invalidate(); + return "redirect:/communityhall/login"; + } + } + // Utility method to ensure distinct by a key private static Predicate distinctByKey(Function keyExtractor) { Set seen = new HashSet<>(); @@ -1012,4 +1029,61 @@ public class HeadquartersController { return response; } + // hall creation newly added by kanimozhi 15062026 + @PostMapping("/saveHallDetails") + public String saveHall( + @RequestParam String hallName, + @RequestParam float depositAmount, + @RequestParam float halfdepositAmt, + @RequestParam float halfDayAmt, + @RequestParam float fullDayAmt, + @RequestParam float gst, + @RequestParam float hallArea, + @RequestParam String ebNumber, + @RequestParam float ebCostPerUnit, + @RequestParam String parkingCapacity, + @RequestParam int seatingCapacity, + @RequestParam String doorNo, + @RequestParam String street, + @RequestParam String area, + @RequestParam String zone, + @RequestParam String division, + @RequestParam(required = false) String landMark, + @RequestParam String city, + @RequestParam int pinCode, + @RequestParam(required = false) String latitude, + @RequestParam(required = false) String longitude, + @RequestParam String hallInchargeName, + @RequestParam long hallInchargeNo, + @RequestParam("hallImages") MultipartFile[] hallImages, + @RequestParam(value = "floorName", required = false) List floorNames, + @RequestParam(value = "floorCapacity", required = false) List floorCapacities, + HttpSession session) { + + String updatedId = (String) session.getAttribute("employeeId"); + hallDetailService.saveHallByHQ(hallName, depositAmount, halfDayAmt, fullDayAmt, gst, hallArea, ebNumber, + ebCostPerUnit, parkingCapacity, seatingCapacity, doorNo, + street, area, zone, division, landMark, city, pinCode, latitude, longitude, hallInchargeName, + hallInchargeNo, updatedId, hallImages, halfdepositAmt, floorNames, floorCapacities); + + return "redirect:/communityhall/headquarters/halldetailslist"; + } + + @GetMapping("/halldetailslist") + public String viewhalldetailsList(Model model, HttpSession session) { + List list = hallDetailsRepository.findAll(); + String headquartersname = (String) session.getAttribute("usertype"); + if (headquartersname != null) { + long mobileno = (long) session.getAttribute("mobileno"); + model.addAttribute("mobileno", mobileno); + model.addAttribute("adminname", headquartersname); + model.addAttribute("halllist", list); + return "headquarters/halldetailslist"; + } else { + session.invalidate(); // Invalidate the session to clear all session attributes + return "redirect:/communityhall/login"; + } + + } + } diff --git a/src/main/java/com/gcc/communityHall/controller/OfficerAPIController.java b/src/main/java/com/gcc/communityHall/controller/OfficerAPIController.java index 337eefff..944a75e3 100644 --- a/src/main/java/com/gcc/communityHall/controller/OfficerAPIController.java +++ b/src/main/java/com/gcc/communityHall/controller/OfficerAPIController.java @@ -1,19 +1,18 @@ package com.gcc.communityHall.controller; -import java.io.FileOutputStream; import java.net.InetAddress; import java.net.UnknownHostException; -import java.time.Instant; import java.time.LocalDate; +import java.util.Arrays; +import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.stream.Collectors; -import ch.qos.logback.core.CoreConstants; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -21,31 +20,26 @@ import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; -import java.net.InetAddress; import com.gcc.communityHall.dto.PaymentsDTO; import com.gcc.communityHall.entity.ApplicationLogs; import com.gcc.communityHall.entity.BookingCalendar; import com.gcc.communityHall.entity.BookingDetails; import com.gcc.communityHall.entity.BookingDetails.BookingStatus; import com.gcc.communityHall.entity.BookingDetails.RefundStatus; -import com.gcc.communityHall.entity.Users.userType; -import com.gcc.communityHall.paymentService.entity.TransactionResponse; -import com.gcc.communityHall.entity.BookingHistory; import com.gcc.communityHall.entity.CounterRefundList; +import com.gcc.communityHall.entity.GccBlockingDate; import com.gcc.communityHall.entity.Settlement; -import com.gcc.communityHall.entity.SettlementHistory; import com.gcc.communityHall.entity.Users; import com.gcc.communityHall.repository.ApplicationLogsRepository; import com.gcc.communityHall.repository.BookingCalendarRepository; import com.gcc.communityHall.repository.BookingDetailsRepository; import com.gcc.communityHall.repository.BookingHistoryRepository; import com.gcc.communityHall.repository.CounterRefundListRepository; -import com.gcc.communityHall.repository.SettlementHistoryRepository; +import com.gcc.communityHall.repository.GccBlockingDateRepository; import com.gcc.communityHall.repository.SettlementRepository; import com.gcc.communityHall.repository.UsersRepository; import com.gcc.communityHall.service.BookingService; @@ -55,7 +49,6 @@ import com.gcc.communityHall.service.ReasonMasterService; import com.gcc.communityHall.service.SettlementService; import com.gcc.communityHall.service.UserService; import com.gcc.communityHall.service.Impl.BookingServiceImpl; -import com.gcc.communityHall.service.Impl.SettlementServiceImpl; import com.gcc.communityHall.service.Impl.UserServiceImpl; import com.gcc.communityHall.service.Impl.WhatsappMsgServiceImpl; @@ -65,50 +58,40 @@ 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("/communityhall/api/officer") @AllArgsConstructor @Validated public class OfficerAPIController { - //ak// ak - @Autowired - private SettlementHistoryRepository settlementHistoryRepository; - + // ak// ak @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 @@ -119,97 +102,85 @@ public class OfficerAPIController { private WhatsappMsgServiceImpl whatsappMsgServiceImpl; @Autowired private PaymentsService paymentsService; + @Autowired - private BookingHistoryRepository bookingHistoryRepository; - + private GccBlockingDateRepository blockingDateRepository; + @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 +202,654 @@ 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(); + } + + // Added for GCC Blocking(New) option + + @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, + @RequestParam("toDate") String toDate, + @RequestParam("hallID") String hallID, + @RequestParam("reasonforblocking") String reasonforblocking, + @RequestParam(value = "selectedBookings", required = false) List selectedBookings, + @RequestParam(value = "description", required = false) String[] descriptions, // Handle descriptions + @RequestParam(value = "document", required = false) MultipartFile[] documents, // Handle documents + HttpSession session) { + + // Your existing logic + String updatedBy = (String) session.getAttribute("employeeId"); + + // Split and convert hall IDs + List hallIdsList = Arrays.stream(hallID.split(",")) + .map(Long::parseLong) + .collect(Collectors.toList()); + + // Call the service with descriptions and 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(); + logs.setComments("Action by " + adminname); + logs.setLoginId(loginid); + logs.setLogType("Gcc Blocking for the Reason:-" + reasonforblocking); + 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 ResponseEntity.ok("Success"); + } + + @Operation(summary = "GCC Block Without Cancelling REST API", description = "REST API to Block halls without cancelling existing bookings (smart slot logic)") + @PostMapping("/blockWithoutCancel") + public ResponseEntity blockWithoutCancel( + @RequestParam("fromDate") String fromDate, + @RequestParam("toDate") String toDate, + @RequestParam("hallID") String hallID, + @RequestParam("reasonforblocking") String reasonforblocking, + @RequestParam(value = "description", required = false) String[] descriptions, + @RequestParam(value = "document", required = false) MultipartFile[] documents, + HttpSession session) { + + String updatedBy = (String) session.getAttribute("employeeId"); + List hallIdsList = Arrays.stream(hallID.split(",")) + .map(Long::parseLong) + .collect(Collectors.toList()); + + bookingService.blockWithoutCancellingBookings(fromDate, toDate, hallIdsList, reasonforblocking, + updatedBy, descriptions, documents); + + 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("Gcc Block Without Cancel for the Reason:-" + reasonforblocking); + 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 ResponseEntity.ok("Success"); + } + + @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 gccBlockedList = blockingDateRepository + .findByFromDateAndToDateBetweenAndHallIdIn(fromDate, toDate, hallIds); + + Map response = new HashMap<>(); + response.put("bookings", bookings); + response.put("blockedEvents", gccBlockedList); + + return ResponseEntity.ok(response); + } + + @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) { + + // Fetch the blocking date entity + GccBlockingDate blockingDate = blockingDateRepository.findById(blockingId).orElse(null); + + if (blockingDate == null) { + return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Blocking ID not found."); + } + + // Get the booking IDs from the blocking date entity (may be null/empty for + // block-only entries) + String bookingIds = blockingDate.getBookingIds(); + String hallIds = blockingDate.getHallId(); + + // Parse booking IDs only if present + List bookingIdList = (bookingIds != null && !bookingIds.trim().isEmpty()) + ? Arrays.stream(bookingIds.split(",")) + .map(String::trim) + .filter(s -> !s.isEmpty()) + .map(Integer::parseInt) + .collect(Collectors.toList()) + : Collections.emptyList(); + + // Convert the hall IDs to a list of longs if provided + List hallIdList = (hallIds != null && !hallIds.trim().isEmpty()) + ? Arrays.stream(hallIds.split(",")) + .map(Long::parseLong) + .collect(Collectors.toList()) + : Collections.emptyList(); + + // Fetch the booking calendar entries within the date range + List bookingCalendars = bookingService.getBookedslots(fromDate, endDate, hallIdList); + + // ── Smart unblock: per-slot decision ────────────────────────────────── + // If morning+evening+is_blocked are all true AND an APPROVED user booking + // exists for that hall/date → only clear is_blocked (leave slots intact). + // Otherwise (GCC-owned slot) → clear everything. + for (BookingCalendar bookingslots : bookingCalendars) { + if (bookingslots.isMorningSlot() && bookingslots.isEveningSlot() && bookingslots.getIs_blocked()) { + List approvedBookings = bookingDetailsRepository.findByHallIdAndDate( + bookingslots.getBdate(), bookingslots.getHallId()); + if (!approvedBookings.isEmpty()) { + // Approved user booking owns the slots — only remove gcc flag + bookingslots.setIs_blocked(false); + } else { + // GCC owned this slot fully — release everything + bookingslots.setBookingId_1(null); + bookingslots.setBookingId_2(null); + bookingslots.setMorningSlot(false); + bookingslots.setEveningSlot(false); + bookingslots.setIs_blocked(false); + } + } else { + // Partial slot scenario — only clear the gcc overlay flag + bookingslots.setIs_blocked(false); + } + bookingCalendarRepository.save(bookingslots); + } + + blockingDate.setBlockedStatus(GccBlockingDate.BlockedStatus.UNBLOCKED); + blockingDateRepository.save(blockingDate); + + // Update GCC_BLOCKED booking_details entries back to GCC_UNBLOCKED + for (int bookingId : bookingIdList) { + Optional bookingDetails = bookingDetailsRepository.findById(bookingId); + if (bookingDetails.isPresent()) { + BookingDetails bookings = bookingDetails.get(); + if (bookings.getBookingStatus() == BookingDetails.BookingStatus.GCC_BLOCKED) { + bookings.setBookingStatus(BookingDetails.BookingStatus.GCC_UNBLOCKED); + bookings.setRefundStatus(BookingDetails.RefundStatus.NA); + bookingDetailsRepository.save(bookings); + } + } + } + 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("Gcc UnBlocking for the Id:-" + blockingDate.getBlockingId()); + 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 ResponseEntity.ok("Success"); + } + + @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() { + List blockedBookings = bookingService.getBlockedEvents(); + + if (blockedBookings.isEmpty()) { + // System.out.println("No blocked bookings found."); + return ResponseEntity.ok(blockedBookings); + } + + for (GccBlockingDate blockedBooking : blockedBookings) { + // System.out.println("Blocked Event: " + blockedBooking); + } + + return ResponseEntity.ok(blockedBookings); + } } diff --git a/src/main/java/com/gcc/communityHall/controller/OfficerController.java b/src/main/java/com/gcc/communityHall/controller/OfficerController.java index 369bad13..f6cd697d 100644 --- a/src/main/java/com/gcc/communityHall/controller/OfficerController.java +++ b/src/main/java/com/gcc/communityHall/controller/OfficerController.java @@ -629,4 +629,24 @@ public class OfficerController { Set seen = new HashSet<>(); return t -> seen.add(keyExtractor.apply(t)); } + + // ── New enhanced GCC Blocking page (does NOT affect the existing page) ── + @GetMapping("/GccblockingNew") + public String viewGccBlockingNew(Model model, HttpSession session) { + String officername = (String) session.getAttribute("usertype"); + if (officername != null && "officer".equals(officername)) { + long mobileno = (long) session.getAttribute("mobileno"); + model.addAttribute("mobileno", mobileno); + model.addAttribute("officername", officername); + String zone = (String) session.getAttribute("zone"); + List hallIds = (List) session.getAttribute("hall_ids"); + model.addAttribute("zone", zone); + model.addAttribute("hallIds", hallIds); + System.out.println("zone" + zone + "\nhallIds.." + hallIds); + return "officer/gccblocking-new"; + } else { + session.invalidate(); + return "redirect:/communityhall/login"; + } + } } diff --git a/src/main/java/com/gcc/communityHall/controller/UserAPIController.java b/src/main/java/com/gcc/communityHall/controller/UserAPIController.java index 6ea23a6c..70e59481 100644 --- a/src/main/java/com/gcc/communityHall/controller/UserAPIController.java +++ b/src/main/java/com/gcc/communityHall/controller/UserAPIController.java @@ -224,8 +224,8 @@ public class UserAPIController { // System.out.println(purpose); // System.out.print("\n MobileNo---:"+mobileNo); Random rand = new Random(); - // int otp = rand.nextInt(90000) + 10000; - int otp = 11111; + int otp = rand.nextInt(90000) + 10000; + // int otp = 11111; System.out.print("\n otp---:" + otp); DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MMM-yyyy%20HH:mm"); LocalDateTime now = LocalDateTime.now(); @@ -238,31 +238,30 @@ public class UserAPIController { System.out.println(urlString); System.out.println("\n urlString---: " + urlString); String bodyMessage = "" + otp; - /* - * try { - * RestTemplate restTemplate = new RestTemplate(); - * String Response = restTemplate.getForObject(urlString, String.class); - * bodyMessage = Response; - * SmsSender sms = new SmsSender(); - * sms.setPhone(MobileNo); - * sms.setCdate(new Date()); - * sms.setBodyMsg(bodyMessage); - * sms.setPurpose(purpose); - * smsSenderRepository.save(sms); - * - * String whatsappMsg = - * "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" - * + MobileNo - * + - * "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Welcome+to+GCC%21+%0A%0AYour+OTP+for+GCC+Community+Centre+is+" - * + otp + "+."; - * String sendMsg = whatsappMsgServiceImpl.sendMsg(whatsappMsg); - * System.out.println("sendwhatsuprepsosne====" + sendMsg); - * } catch (Exception e) { - * // System.out.print("ERROR in Sending---: "+e); - * bodyMessage = "Error"; - * } - */ + + try { + RestTemplate restTemplate = new RestTemplate(); + String Response = restTemplate.getForObject(urlString, String.class); + bodyMessage = Response; + SmsSender sms = new SmsSender(); + sms.setPhone(MobileNo); + sms.setCdate(new Date()); + sms.setBodyMsg(bodyMessage); + sms.setPurpose(purpose); + smsSenderRepository.save(sms); + + String whatsappMsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + + MobileNo + + + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Welcome+to+GCC%21+%0A%0AYour+OTP+for+GCC+Community+Centre+is+" + + otp + "+."; + String sendMsg = whatsappMsgServiceImpl.sendMsg(whatsappMsg); + System.out.println("sendwhatsuprepsosne====" + sendMsg); + } catch (Exception e) { + // System.out.print("ERROR in Sending---: "+e); + bodyMessage = "Error"; + } + HttpSession session = request.getSession(); session.setAttribute("otp", otp); return bodyMessage; @@ -411,9 +410,8 @@ public class UserAPIController { @Operation(summary = "Past Data from the booking Calendar Hall REST API", description = "REST API to Retrieve the Pat Data from booking calendar") // Getting the Past Data from the Calendar @GetMapping("/getPastData") - public List getPastData(@RequestParam("hall_id") int hall_id) { - List data = new ArrayList(); - data = bookingService.getPastData(hall_id); + public List> getPastData(@RequestParam("hall_id") int hall_id) { + List> data = bookingService.getPastData(hall_id); if (data != null) { return data; } diff --git a/src/main/java/com/gcc/communityHall/entity/FloorDetails.java b/src/main/java/com/gcc/communityHall/entity/FloorDetails.java index 6c54831a..fe8746b9 100644 --- a/src/main/java/com/gcc/communityHall/entity/FloorDetails.java +++ b/src/main/java/com/gcc/communityHall/entity/FloorDetails.java @@ -13,62 +13,88 @@ import jakarta.persistence.ManyToOne; @Entity public class FloorDetails { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private int floorId; - - @Column(name = "floor") - private String floor; - @ManyToOne(cascade = CascadeType.PERSIST,fetch = FetchType.LAZY) - @JsonIgnore - private HallDetails hallDetails; - - @Column(name="area") - private double hallarea; - - - public HallDetails getHallDetails() { - return hallDetails; - } - - public void setHallDetails(HallDetails hallDetails) { - this.hallDetails = hallDetails; - } - - public int getFloorId() { - return floorId; - } - - public void setFloorId(int floorId) { - this.floorId = floorId; - } - - public String getFloor() { - return floor; - } - - public void setFloor(String floor) { - this.floor = floor; - } - - public double getHallarea() { - return hallarea; - } - - public void setHallarea(double hallarea) { - this.hallarea = hallarea; - } - - public FloorDetails(int floorId, String floor, HallDetails hallDetails, double hallarea) { - super(); - this.floorId = floorId; - this.floor = floor; - this.hallDetails = hallDetails; - this.hallarea = hallarea; - } - - public FloorDetails() { - super(); - } - + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private int floorId; + + @Column(name = "floor") + private String floor; + + @ManyToOne(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY) + @JsonIgnore + private HallDetails hallDetails; + + @Column(name = "area") + private double hallarea; + + @Column(name = "is_active", nullable = false, columnDefinition = "BOOLEAN DEFAULT true") + private boolean isActive = true; + + @Column(name = "is_delete", nullable = false, columnDefinition = "BOOLEAN DEFAULT false") + private boolean isDelete = false; + + // ── Getters & Setters ────────────────────────────────────────────────────── + + public HallDetails getHallDetails() { + return hallDetails; + } + + public void setHallDetails(HallDetails hallDetails) { + this.hallDetails = hallDetails; + } + + public int getFloorId() { + return floorId; + } + + public void setFloorId(int floorId) { + this.floorId = floorId; + } + + public String getFloor() { + return floor; + } + + public void setFloor(String floor) { + this.floor = floor; + } + + public double getHallarea() { + return hallarea; + } + + public void setHallarea(double hallarea) { + this.hallarea = hallarea; + } + + public boolean isActive() { + return isActive; + } + + public void setActive(boolean isActive) { + this.isActive = isActive; + } + + public boolean isDelete() { + return isDelete; + } + + public void setDelete(boolean isDelete) { + this.isDelete = isDelete; + } + + // ── Constructors ─────────────────────────────────────────────────────────── + + public FloorDetails(int floorId, String floor, HallDetails hallDetails, double hallarea) { + super(); + this.floorId = floorId; + this.floor = floor; + this.hallDetails = hallDetails; + this.hallarea = hallarea; + } + + public FloorDetails() { + super(); + } } diff --git a/src/main/java/com/gcc/communityHall/entity/HallDetails.java b/src/main/java/com/gcc/communityHall/entity/HallDetails.java index bd32cb8c..f3dbd901 100644 --- a/src/main/java/com/gcc/communityHall/entity/HallDetails.java +++ b/src/main/java/com/gcc/communityHall/entity/HallDetails.java @@ -5,6 +5,7 @@ import java.util.Date; import java.util.List; import com.fasterxml.jackson.annotation.JsonIgnore; +import org.hibernate.annotations.SQLRestriction; import jakarta.persistence.CascadeType; import jakarta.persistence.Column; @@ -45,6 +46,7 @@ public class HallDetails { private List hallImagesList; @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "hallDetails") + @SQLRestriction("is_active = true AND is_delete = false") private List floorDetailsList; @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "hallDetails") 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 3ef7b23f..32173985 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,72 @@ 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 " + + @Query(value = "SELECT tr.booking_id, tr.hall_id, tr.amount, tr.status_code, tr.txansaction_id, tr.user_id, tr.tpsl_txn_id " + + + // ", 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,8 +85,8 @@ 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) diff --git a/src/main/java/com/gcc/communityHall/repository/BookingCalendarRepository.java b/src/main/java/com/gcc/communityHall/repository/BookingCalendarRepository.java index c71f6607..1c12b11d 100644 --- a/src/main/java/com/gcc/communityHall/repository/BookingCalendarRepository.java +++ b/src/main/java/com/gcc/communityHall/repository/BookingCalendarRepository.java @@ -14,65 +14,77 @@ import org.springframework.stereotype.Repository; import com.gcc.communityHall.entity.BookingCalendar; @Repository -public interface BookingCalendarRepository extends JpaRepository { +public interface BookingCalendarRepository extends JpaRepository { - @Query(value="SELECT booking_id_1 , booking_id_2 FROM booking_calendar\r\n" + @Query(value = "SELECT booking_id_1 , booking_id_2 FROM booking_calendar\r\n" + "WHERE hall_id=:hallID AND bdate BETWEEN :fromDate AND :toDate", nativeQuery = true) List getCancelling(String fromDate, String toDate, String hallID); - @Query(value="select * from booking_calendar where hall_id=:hallID and bdate=:aa", nativeQuery = true) + @Query(value = "select * from booking_calendar where hall_id=:hallID and bdate=:aa", nativeQuery = true) BookingCalendar getbyDates(LocalDate aa, String hallID); - @Query(value="SELECT * FROM booking_calendar WHERE (booking_id_1=:bookID or booking_id_2=:bookID)",nativeQuery = true) + @Query(value = "SELECT * FROM booking_calendar WHERE (booking_id_1=:bookID or booking_id_2=:bookID)", nativeQuery = true) List getCancellingdata1(String bookID); - + @Query("SELECT c FROM BookingCalendar c WHERE c.bookingId_1 = :bookingId OR c.bookingId_2 = :bookingId") BookingCalendar getSingleCancellingData(@Param("bookingId") String bookingId); - BookingCalendar findByBdateAndHallId(LocalDate bdate, int hallId); + BookingCalendar findByBdateAndHallId(LocalDate bdate, int hallId); - @Query(value=" select * FROM booking_calendar where hall_id =:hall_id AND bdate BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 6 MONTH)", nativeQuery = true) - List getPastData(int hall_id); + // @Query(value=" select * FROM booking_calendar where hall_id =:hall_id AND + // bdate BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 6 MONTH)", + // nativeQuery = true) + // List getPastData(int hall_id); + @Query(value = "select bc.bdate, bc.morning_slot, bc.evening_slot, bc.is_blocked , ifnull(bd1.booking_status,'NA') as booking_status1, " + + + "ifnull(bd2.booking_status,'NA') as booking_status2 FROM booking_calendar bc " + + "left join booking_details bd1 on bc.booking_id_1 = bd1.booking_id " + + "left join booking_details bd2 on bc.booking_id_2 = bd2.booking_id " + + "where bc.hall_id =:hall_id AND bc.bdate BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 6 MONTH)", nativeQuery = true) + List> getPastData(int hall_id); - @Query(value = "SELECT hall_id FROM booking_calendar where (bdate BETWEEN DATE_FORMAT(:fromDate, '%Y-%m-%d') AND DATE_FORMAT(:toDate, '%Y-%m-%d')) AND hall_id = :hall_id group by hall_id",nativeQuery = true) + @Query(value = "SELECT hall_id FROM booking_calendar where (bdate BETWEEN DATE_FORMAT(:fromDate, '%Y-%m-%d') AND DATE_FORMAT(:toDate, '%Y-%m-%d')) AND hall_id = :hall_id group by hall_id", nativeQuery = true) List groupByHallIdToRemov(String fromDate, String toDate, int hall_id); @Query(value = " select * from booking_calendar where hall_id =:hallId and bdate BETWEEN :fromDate and :toDate order by hall_id", nativeQuery = true) - List getCalendarByBDateAndHAllId(String fromDate, String toDate, int hallId); + List getCalendarByBDateAndHAllId(String fromDate, String toDate, int hallId); @Query(value = " select * from booking_calendar where bdate BETWEEN :fromDate and :toDate order by hall_id", nativeQuery = true) - List getCalendarByBDate(String fromDate, String toDate); - - @Query(value = "SELECT SUM(CASE WHEN booking_status = 'APPROVED' THEN 1 ELSE 0 END) AS approved_booking_count,\r\n" - + "SUM(CASE WHEN booking_status = 'REJECTED' THEN 1 ELSE 0 END) AS rejected_booking_count,\r\n" - + "SUM(CASE WHEN refund_status = 'WAITING' THEN 1 ELSE 0 END) AS waiting_settlement_count,\r\n" - + "SUM(CASE WHEN refund_status = 'APPROVED' THEN 1 ELSE 0 END) AS approved_settlement_count,\r\n" - + "SUM(CASE WHEN refund_status = 'REJECTED' THEN 1 ELSE 0 END) AS reject_settlement_count\r\n" - + "FROM booking_details;",nativeQuery = true) - List> toatlBookingCount(); - - @Query(value = "SELECT * FROM booking_calendar WHERE hall_id IN (:hallIdList) AND bdate BETWEEN :fromDate AND :endDate", nativeQuery = true) - List findByHallIdAndDateRange(@Param("fromDate") LocalDate fromDate, @Param("endDate") LocalDate endDate, @Param("hallIdList") List hallIdList); - - @Modifying - @Query("UPDATE BookingCalendar bc SET bc.bdate = :newDate WHERE (bc.bookingId_1 = :bookingId OR bc.bookingId_2 = :bookingId) AND bc.bdate = :currentDate") - void updateBdateByBookingIdAndDate(@Param("newDate") LocalDate newDate, @Param("bookingId") String bookingId, @Param("currentDate") LocalDate currentDate); + List getCalendarByBDate(String fromDate, String toDate); + + @Query(value = "SELECT SUM(CASE WHEN booking_status = 'APPROVED' THEN 1 ELSE 0 END) AS approved_booking_count,\r\n" + + "SUM(CASE WHEN booking_status = 'REJECTED' THEN 1 ELSE 0 END) AS rejected_booking_count,\r\n" + + "SUM(CASE WHEN refund_status = 'WAITING' THEN 1 ELSE 0 END) AS waiting_settlement_count,\r\n" + + "SUM(CASE WHEN refund_status = 'APPROVED' THEN 1 ELSE 0 END) AS approved_settlement_count,\r\n" + + "SUM(CASE WHEN refund_status = 'REJECTED' THEN 1 ELSE 0 END) AS reject_settlement_count\r\n" + + "FROM booking_details;", nativeQuery = true) + List> toatlBookingCount(); + + @Query(value = "SELECT * FROM booking_calendar WHERE hall_id IN (:hallIdList) AND bdate BETWEEN :fromDate AND :endDate", nativeQuery = true) + List findByHallIdAndDateRange(@Param("fromDate") LocalDate fromDate, + @Param("endDate") LocalDate endDate, @Param("hallIdList") List hallIdList); + + @Modifying + @Query("UPDATE BookingCalendar bc SET bc.bdate = :newDate WHERE (bc.bookingId_1 = :bookingId OR bc.bookingId_2 = :bookingId) AND bc.bdate = :currentDate") + void updateBdateByBookingIdAndDate(@Param("newDate") LocalDate newDate, @Param("bookingId") String bookingId, + @Param("currentDate") LocalDate currentDate); + Optional findByBdate(LocalDate bdate); - @Query(value = "SELECT bc.bdate, bc.booking_id_1, bc.booking_id_2, bc.morning_slot, bc.evening_slot, hd.hall_name, hd.hall_id " + + @Query(value = "SELECT bc.bdate, bc.booking_id_1, bc.booking_id_2, bc.morning_slot, bc.evening_slot, hd.hall_name, hd.hall_id " + + "FROM booking_calendar bc " + "JOIN hall_details hd ON bc.hall_id = hd.hall_id " + "WHERE bc.bdate >= :fromDate " + "AND bc.bdate <= :toDate " + "AND (:bookingId IS NULL OR (bc.booking_id_1 = :bookingId OR bc.booking_id_2 = :bookingId)) " + - "AND (:hallName = '' OR hd.hall_name = :hallName)", - nativeQuery = true) + "AND (:hallName = '' OR hd.hall_name = :hallName)", nativeQuery = true) List findBookingCalendarDetails(@Param("fromDate") String fromDate, - @Param("toDate") String toDate, - @Param("bookingId") Long bookingId, - @Param("hallName") String hallName); + @Param("toDate") String toDate, + @Param("bookingId") Long bookingId, + @Param("hallName") String hallName); - @Query(value="SELECT * from booking_calendar where booking_id_1 = :bookingId or booking_id_2 = :bookingId ", nativeQuery = true) - List getCalendarByBookingId(int bookingId); + @Query(value = "SELECT * from booking_calendar where booking_id_1 = :bookingId or booking_id_2 = :bookingId ", nativeQuery = true) + List getCalendarByBookingId(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 47439991..ffd27ee6 100644 --- a/src/main/java/com/gcc/communityHall/repository/BookingDetailsRepository.java +++ b/src/main/java/com/gcc/communityHall/repository/BookingDetailsRepository.java @@ -1718,4 +1718,7 @@ public interface BookingDetailsRepository extends JpaRepository getCounterWiseBookingList(String fromDate, String toDate); + + @Query("select bd from BookingDetails bd where DATE(bd.startDate) = :date and bd.hallDetails.hallId = :hallId and bd.bookingStatus in ('APPROVED','WAITING_FOR_NOC','WAITING_FOR_NOC_APPROVAL') ") + List findByHallIdAndDate(@Param("date") LocalDate date, @Param("hallId") Integer hallId); } diff --git a/src/main/java/com/gcc/communityHall/repository/FloorDetailsRepository.java b/src/main/java/com/gcc/communityHall/repository/FloorDetailsRepository.java index 5082739e..aa75df48 100644 --- a/src/main/java/com/gcc/communityHall/repository/FloorDetailsRepository.java +++ b/src/main/java/com/gcc/communityHall/repository/FloorDetailsRepository.java @@ -1,10 +1,30 @@ package com.gcc.communityHall.repository; +import java.util.List; + import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; + import com.gcc.communityHall.entity.FloorDetails; @Repository -public interface FloorDetailsRepository extends JpaRepository { +public interface FloorDetailsRepository extends JpaRepository { + + /** Fetch all rows (used internally only). */ + List findByHallDetails_HallId(int hallId); + + /** Fetch only active, non-deleted floor rows for a hall. */ + List findByHallDetails_HallIdAndIsActiveAndIsDelete(int hallId, boolean isActive, boolean isDelete); + + /** Soft-delete: mark existing active floors as inactive & deleted. */ + @Modifying + @Query("UPDATE FloorDetails f SET f.isActive = false, f.isDelete = true " + + "WHERE f.hallDetails.hallId = :hallId AND f.isActive = true AND f.isDelete = false") + void softDeleteByHallId(@Param("hallId") int hallId); + /** Hard-delete (kept for backward-compat but no longer used in HQ flow). */ + void deleteByHallDetails_HallId(int hallId); } diff --git a/src/main/java/com/gcc/communityHall/repository/GccBlockingDateRepository.java b/src/main/java/com/gcc/communityHall/repository/GccBlockingDateRepository.java index 3b55d77b..61689ed7 100644 --- a/src/main/java/com/gcc/communityHall/repository/GccBlockingDateRepository.java +++ b/src/main/java/com/gcc/communityHall/repository/GccBlockingDateRepository.java @@ -14,26 +14,31 @@ import com.gcc.communityHall.entity.GccBlockingDate; import com.gcc.communityHall.entity.GccBlockingDate.BlockedStatus; @Repository -public interface GccBlockingDateRepository extends JpaRepository { +public interface GccBlockingDateRepository extends JpaRepository { @Query(value = "SELECT * FROM gcc_blocking_date WHERE hall_id IN (:hallIds) AND blocked_status = 'BLOCKED' AND start_date BETWEEN :fromDate AND :toDate ", nativeQuery = true) - List findByFromDateAndToDateBetweenAndHallIdIn(LocalDate fromDate, LocalDate toDate, List hallIds); + List findByFromDateAndToDateBetweenAndHallIdIn(LocalDate fromDate, LocalDate toDate, + List hallIds); - @Query("SELECT g FROM GccBlockingDate g WHERE g.hallId = :hallId AND g.blockedStatus = :blockedStatus") - List findAllByHallIdAndBlockedStatus(@Param("hallId") String hallId, @Param("blockedStatus") GccBlockingDate.BlockedStatus blockedStatus); + @Query("SELECT g FROM GccBlockingDate g WHERE g.hallId = :hallId AND g.blockedStatus = :blockedStatus") + List findAllByHallIdAndBlockedStatus(@Param("hallId") String hallId, + @Param("blockedStatus") GccBlockingDate.BlockedStatus blockedStatus); - @Query("SELECT g FROM GccBlockingDate g WHERE g.blockedStatus = 'BLOCKED' AND g.startDate >= CURRENT_DATE") - List findAllBlocked(); + @Query("SELECT g FROM GccBlockingDate g WHERE g.blockedStatus = 'BLOCKED' AND g.endDate >= CURRENT_DATE") + List findAllBlocked(); @Query("SELECT g FROM GccBlockingDate g WHERE g.blockingReason = :blockingReason AND g.startDate <= :endDate AND g.endDate >= :startDate") - List findByBlockingReasonAndDateRange( @Param("blockingReason") String blockingReason,@Param("startDate") Date startDate,@Param("endDate") Date endDate); + List findByBlockingReasonAndDateRange(@Param("blockingReason") String blockingReason, + @Param("startDate") Date startDate, @Param("endDate") Date endDate); @Query("SELECT COUNT(DISTINCT g.hallId) FROM GccBlockingDate g WHERE g.blockingReason = :blockingReason AND g.startDate <= :endDate AND g.endDate >= :startDate") - int countBlockedHallsInDateRange(@Param("blockingReason") String blockingReason,@Param("startDate") Date startDate,@Param("endDate") Date endDate); + int countBlockedHallsInDateRange(@Param("blockingReason") String blockingReason, @Param("startDate") Date startDate, + @Param("endDate") Date endDate); @Query("SELECT COUNT(b) FROM GccBlockingDate b WHERE b.hallId = :hallId AND b.blockedStatus = 'BLOCKED' AND b.startDate BETWEEN :startDate AND :endDate") - int countBlockedBookings(@Param("hallId") int hallId, @Param("startDate") Date startDate, @Param("endDate") Date endDate); - - @Query(value = "SELECT * FROM gcc_blocking_date WHERE FIND_IN_SET(:bookingId, booking_ids) > 0", nativeQuery = true) - List getByBookingId(@Param("bookingId") int bookingId); + int countBlockedBookings(@Param("hallId") int hallId, @Param("startDate") Date startDate, + @Param("endDate") Date endDate); + + @Query(value = "SELECT * FROM gcc_blocking_date WHERE FIND_IN_SET(:bookingId, booking_ids) > 0", nativeQuery = true) + List getByBookingId(@Param("bookingId") int bookingId); } diff --git a/src/main/java/com/gcc/communityHall/service/BookingService.java b/src/main/java/com/gcc/communityHall/service/BookingService.java index 6fd64e53..62760618 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; @@ -18,211 +17,242 @@ import com.gcc.communityHall.entity.EbDetails; import com.gcc.communityHall.entity.GccBlockingDate; 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); - 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 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 Map saveBookingDetails(Map formData); + public BookingDetails updateBookingStatustoGCCBlocked(BookingDetails bookingDetails); - public BookingDetails updateBookingStatustoGCCBlocked(BookingDetails bookingDetails); + public BookingDetails updateBookingStatus(int bookingId, BookingDetails.BookingStatus status, String comments); - public BookingDetails updateBookingStatus(int bookingId, BookingDetails.BookingStatus status, String comments); + public BookingDetails updateBookingStatusById(int bookingId, BookingDetails.BookingStatus status, String comments); - public BookingDetails updateBookingStatusById(int bookingId, BookingDetails.BookingStatus status, String comments); + public EbDetails updateEbDetails(int bookingId, double startUnit, double endUnit, char status); - public EbDetails updateEbDetails(int bookingId, double startUnit, double endUnit, char status); + // typeOfCancel depends { } + String cancelBooking(int bookingId, BookingDetails.BookingStatus currentStatus, String comments); - //typeOfCancel depends { } - String cancelBooking(int bookingId, BookingDetails.BookingStatus currentStatus, String comments); + public String confirmBooking(int bookingId); - public String confirmBooking(int bookingId); + public BookingDetails getBookingDetailsWithSettlement(int settlementId); - public BookingDetails getBookingDetailsWithSettlement(int settlementId); + // sreeja + List getPresentsEventsByUserId(Integer hallId); + List getPastsEventsByUserId(Integer hallId); - //sreeja - List getPresentsEventsByUserId(Integer hallId); + List getFuturesEventsByUserId(Integer hallId); - List getPastsEventsByUserId(Integer hallId); + List getSettlementList(Integer hallId); - List getFuturesEventsByUserId(Integer hallId); + public List getFilteredBookings(LocalDate fromDate, LocalDate toDate, List hallIds); - List getSettlementList(Integer hallId); + public List> getPastData(int hall_id); - public List getFilteredBookings(LocalDate fromDate, LocalDate toDate, List hallIds); + 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[]); - public List getPastData(int hall_id); + public int checkUserBookinglimitation(int userId); - 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 getAllBookingsByUserId(Integer userId); - public int checkUserBookinglimitation(int userId); + List> getAllBookingEventsByUserId(Integer userId); - List getAllBookingsByUserId(Integer userId); + // List getAllBookingDetailsWithStatus(String fromDate, String + // toDate, String bookingStatus); - List> getAllBookingEventsByUserId(Integer userId); + // List getAllPaymentsDetails( String fromDate, String toDate); + List getBookingUserDetailsReport(String fromDate, String toDate); - //List getAllBookingDetailsWithStatus(String fromDate, String toDate, String bookingStatus); + List getBookingHallDetailsReport(String fromDate, String toDate); - //List getAllPaymentsDetails( String fromDate, String toDate); + List getBlockedEvents(LocalDate fromDate, LocalDate toDate, List hallIds); - List getBookingUserDetailsReport(String fromDate, String toDate); + List> getOfflineBookings(); - List getBookingHallDetailsReport(String fromDate, String toDate); + List getBookedslots(LocalDate fromDate, LocalDate endDate, List hallIdList); - List getBlockedEvents(LocalDate fromDate, LocalDate toDate, List hallIds); + BookingDetails updateCancelledBookingStatus(int bookingId, BookingStatus status, String comments); - List> getOfflineBookings(); + BookingDetails updateRefundStatus(int bookingId, RefundStatus status); - List getBookedslots(LocalDate fromDate, LocalDate endDate, List hallIdList); + // officer service + List getAllBookingDetailsByZone(String fromDate, String toDate, String zone); - BookingDetails updateCancelledBookingStatus(int bookingId, BookingStatus status, String comments); + List getAllBookingDetailsByZoneWithStatus(String fromDate, String toDate, String zone, + String bookingStatus); - BookingDetails updateRefundStatus(int bookingId, RefundStatus status); + List getAllPaymentsDetailsByZone(String fromDate, String toDate, String zone); - //officer service - List getAllBookingDetailsByZone(String fromDate, String toDate, String zone); + List getBookingHallDetailsReportByZone(String fromDate, String toDate, String zone); - List getAllBookingDetailsByZoneWithStatus(String fromDate, String toDate, String zone, String bookingStatus); + Optional updateBookingDatesAndCalendar(int bookingId, String startDate, String endDate); - List getAllPaymentsDetailsByZone(String fromDate, String toDate, String zone); + List getBookingHallDetailsReportByZone1(String fromDate, String toDate, String zone, Integer hallId); - List getBookingHallDetailsReportByZone(String fromDate, String toDate, String zone); + List getGccBlockingEvents(String hallId); - Optional updateBookingDatesAndCalendar(int bookingId, String startDate, String endDate); + int getBlockedHallCount(String blockingReason, Date startDate, Date endDate); - List getBookingHallDetailsReportByZone1(String fromDate, String toDate, String zone, Integer hallId); + @Transactional + void cancelAllBookings(String fromDate, String toDate, List hallIdsList, + String reasonforblocking, List selectedBookings, String updatedBy, String[] descriptions, + MultipartFile[] documents); - List getGccBlockingEvents(String hallId); + @Transactional + void blockWithoutCancellingBookings(String fromDate, String toDate, List hallIdsList, + String reasonforblocking, String updatedBy, String[] descriptions, + MultipartFile[] documents); - int getBlockedHallCount(String blockingReason, Date startDate, Date endDate); + List findBookingDetailsByBookingId(Long bookingId); - @Transactional - void cancelAllBookings(String fromDate, String toDate, List hallIdsList, - String reasonforblocking, List selectedBookings, String updatedBy, String[] descriptions, MultipartFile[] documents); + // admin dashboard + Map> getBookingStatistics(LocalDate fromDate, LocalDate toDate, String zone, + String division, Integer hallid, String userType); - List findBookingDetailsByBookingId(Long bookingId); + public List> getBookingDetailsByHallId(int hallId); - //admin dashboard - Map> getBookingStatistics(LocalDate fromDate, LocalDate toDate, String zone, String division, Integer hallid, String userType); + // officer dashboard + Map> getOfficerDashboard(LocalDate fromDate, LocalDate toDate, String zone, + String division, Integer hallid, String userType); - public List> getBookingDetailsByHallId(int hallId); + List> getHallDetailsForOfficer(Integer hallIid); + // List getAllPaymentsDetails(String fromDate, String toDate, String + // paymentStatus); + // admin reports - //officer dashboard - Map> getOfficerDashboard(LocalDate fromDate, LocalDate toDate, String zone, String division, Integer hallid, String userType); + List getBookingDetailsByBookingDate(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 getBookingDetailsByEventDate(String fromDate, String toDate, String zone, String division, + Integer hallid); - List getBookingDetailsByBookingDate(String fromDate, String toDate, String zone, String division, Integer hallid); + List getBookingDetailsByBookingDateWithStatus(String fromDate, String toDate, String bookingStatus, + String zone, String division, Integer hallid); - List getBookingDetailsByEventDate(String fromDate, String toDate, String zone, String division, Integer hallid); + List getBookingDetailsByEventDateWithStatus(String fromDate, String toDate, String bookingStatus, + String zone, String division, Integer hallid); - List getBookingDetailsByBookingDateWithStatus(String fromDate, String toDate, String bookingStatus, String zone, String division, Integer hallid); + List getAllPaymentsDetails(String fromDate, String toDate, String paymentStatus, String zone, + String division, Integer hallid); - List getBookingDetailsByEventDateWithStatus(String fromDate, String toDate, String bookingStatus, String zone, String division, Integer hallid); + List getBookingHallDetailsReportByBookingDate(String fromDate, String toDate, String zone, String division, + Integer hallid); - List getAllPaymentsDetails(String fromDate, String toDate, String paymentStatus, String zone, String division, Integer hallid); + List getBookingHallDetailsReportByEventDate(String fromDate, String toDate, String zone, String division, + Integer hallid); - List getBookingHallDetailsReportByBookingDate(String fromDate, String toDate, String zone, String division, Integer hallid); + List getAllBookingsettlementDetailsByBookingDate(String fromDate, String toDate); - List getBookingHallDetailsReportByEventDate(String fromDate, String toDate, String zone, String division, Integer hallid); + List getAllBookingsettlementDetailsByBookingDateWithStatus(String fromDate, String toDate, + String refundStatus); - List getAllBookingsettlementDetailsByBookingDate(String fromDate, String toDate); + List getAllBookingsettlementDetailsByEventDate(String fromDate, String toDate); - List getAllBookingsettlementDetailsByBookingDateWithStatus(String fromDate, String toDate, String refundStatus); + List getAllBookingsettlementDetailsByEventDateWithStatus(String fromDate, String toDate, + String refundStatus); - List getAllBookingsettlementDetailsByEventDate(String fromDate, String toDate); + List getAllBookingDetailsBookingDateByZone(String fromDate, String toDate, String zone); - List getAllBookingsettlementDetailsByEventDateWithStatus(String fromDate, String toDate, String refundStatus); + List getAllBookingDetailsEventDateByZone(String fromDate, String toDate, String zone); - List getAllBookingDetailsBookingDateByZone(String fromDate, String toDate, String zone); + List getAllBookingDetailsBookingDateByZoneWithStatus(String fromDate, String toDate, String zone, + String bookingStatus); - List getAllBookingDetailsEventDateByZone(String fromDate, String toDate, String zone); + List getAllBookingDetailsEventDateByZoneWithStatus(String fromDate, String toDate, String zone, + String bookingStatus); - List getAllBookingDetailsBookingDateByZoneWithStatus(String fromDate, String toDate, String zone, String bookingStatus); + List getAllBookingsettlementDetailsByZoneByBookingDate(String fromDate, String toDate, String zone); - List getAllBookingDetailsEventDateByZoneWithStatus(String fromDate, String toDate, String zone, String bookingStatus); + List getAllBookingsettlementDetailsByZoneByEventDate(String fromDate, String toDate, String zone); - List getAllBookingsettlementDetailsByZoneByBookingDate(String fromDate, String toDate, String zone); + List getAllBookingsettlementDetailsByZoneByBookingDateWithStatus(String fromDate, String toDate, + String zone, String refundStatus); - List getAllBookingsettlementDetailsByZoneByEventDate(String fromDate, String toDate, String zone); + List getAllBookingsettlementDetailsByZoneByEventDateWithStatus(String fromDate, String toDate, + String zone, String refundStatus); - List getAllBookingsettlementDetailsByZoneByBookingDateWithStatus(String fromDate, String toDate, String zone, String refundStatus); + List getBookingHallDetailsReportByZoneByBookingDate(String fromDate, String toDate, String zone); - List getAllBookingsettlementDetailsByZoneByEventDateWithStatus(String fromDate, String toDate, String zone, String refundStatus); + List getBookingHallDetailsReportByZoneByEventDate(String fromDate, String toDate, String zone); - List getBookingHallDetailsReportByZoneByBookingDate(String fromDate, String toDate, String zone); + List getBookingHallDetailsReportByZoneByBookingDateHallname(String fromDate, String toDate, String zone, + Integer hallId); - List getBookingHallDetailsReportByZoneByEventDate(String fromDate, String toDate, String zone); + List getBookingHallDetailsReportByZoneByEventDateHallname(String fromDate, String toDate, String zone, + Integer hallId); - List getBookingHallDetailsReportByZoneByBookingDateHallname(String fromDate, String toDate, String zone, Integer hallId); + BookingDetails saveebdetails(int bookingId, double startingReading, MultipartFile startingReadingimage); - List getBookingHallDetailsReportByZoneByEventDateHallname(String fromDate, String toDate, String zone, Integer hallId); + String confirmStateBooking(int bookingId); - BookingDetails saveebdetails(int bookingId, double startingReading, MultipartFile startingReadingimage); + String uploadNOCFile(MultipartFile file, int bookingId); - String confirmStateBooking(int bookingId); + // gccapps + List getApprovedBookingDetails(); - String uploadNOCFile(MultipartFile file, int bookingId); + List getRejectedBookingDetails(); - //gccapps - List getApprovedBookingDetails(); + List getAllPaymentsDetails(String fromDate, String toDate); - List getRejectedBookingDetails(); + List getPastsEvents(); - List getAllPaymentsDetails(String fromDate, String toDate); + List getPresentsEvents(); - List getPastsEvents(); + List getFuturesEvents(); - List getPresentsEvents(); + List getSettlementApprovedList(); - List getFuturesEvents(); + List> getHallDetails(Integer hall_id); - List getSettlementApprovedList(); + List getWaitingforNOCapproval(); - List> getHallDetails(Integer hall_id); + List getAllExtraPaymentsDetails(String fromDate, String toDate, String paymentStatus, String zone, + String division, Integer hallid); - List getWaitingforNOCapproval(); + // developer + List getTransactionresponse(String fromDate, String toDate, Long bookingId, Long hallId); - List getAllExtraPaymentsDetails(String fromDate, String toDate, String paymentStatus, String zone, String division, Integer hallid); + List getRefundResponse(String fromDate, String toDate, Long bookingId); - //developer - List getTransactionresponse(String fromDate, String toDate, Long bookingId, Long hallId); + List getBookingCalendarDetails(String fromDate, String toDate, Long bookingId, String hallName); - List getRefundResponse(String fromDate, String toDate, Long bookingId); + List getBookingsByDateAndHall(String bookingDate, Long hallId); - List getBookingCalendarDetails(String fromDate, String toDate, Long bookingId, String hallName); + BookingDetails updateRefundStatusScheduler(int bookingId, RefundStatus status); - List getBookingsByDateAndHall(String bookingDate, Long hallId); + List getCounterWiseBookingCount(String fromDate, String toDate); - BookingDetails updateRefundStatusScheduler(int bookingId, RefundStatus status); + List getHallWiseBookingDetails(String fromDate, String toDate, String CounterId); - List getCounterWiseBookingCount(String fromDate, String toDate); + List getBookingDetailsForAllHalls(String fromDate, String toDate, String CounterId, Integer hallid); - List getHallWiseBookingDetails(String fromDate, String toDate, String CounterId); + List getCounterWiseBookingDetails(String fromDate, String toDate); - List getBookingDetailsForAllHalls(String fromDate, String toDate, String CounterId, Integer hallid); + List getZoneWiseBookingList(String fromDate, String toDate); - List getCounterWiseBookingDetails(String fromDate, String toDate); + List getAllHallWiseBookingList(String fromDate, String toDate); - List getZoneWiseBookingList(String fromDate, String toDate); + List getAllCounterWiseBookingList(String fromDate, String toDate); - List getAllHallWiseBookingList(String fromDate, String toDate); + // ak + List getSettlementInitiatedReport(String fromDate, String toDate); - List getAllCounterWiseBookingList(String fromDate, String toDate); - //ak - List getSettlementInitiatedReport(String fromDate, String toDate); + List getBlockedEvents(); } diff --git a/src/main/java/com/gcc/communityHall/service/HallDetailService.java b/src/main/java/com/gcc/communityHall/service/HallDetailService.java index e293d15e..70d1274f 100644 --- a/src/main/java/com/gcc/communityHall/service/HallDetailService.java +++ b/src/main/java/com/gcc/communityHall/service/HallDetailService.java @@ -12,39 +12,70 @@ import com.gcc.communityHall.entity.HallImages; public interface HallDetailService { - HallDetails saveHallDetails(HallDetails hallDetails, List hallImages); - HallDetails getHallById(int hallId); - HallDetails deActivateHallById(int hallId); - - HallDetails saveHall( - String hallName, - float depositAmount, - float halfDayAmt, float fullDayAmt, - float gst ,float hallArea, String ebNumber, float ebCostPerUnit, - int parkingCapacity, int seatingCapacity, - String doorNo, String street, - String area, String zone, - String division, String landMark, - String city, - int pinCode,String latitude, - String longitude, String hallInchargeName, - long hallInchargeNo, - String updatedId, - MultipartFile hallImages[], float halfDepositAmt ); - List getHallImages(int hallId); - - String updateHallDetail(HallDetails hallDetails, List images); - - List removeHallById(HashSet hallIds); - List getHallNames(); - void saveHallImage(Long hallId, MultipartFile file) throws IOException; - List getHallImagesByHallId(Long hallId); - List getHallNamesbyzone(String zone); - - public Map getHallsDetailsByZone(String zone); - //officerDashboard - public Map getHallsDetailsForOfficer(String zone); - void updatenewHallImages(Integer hallId, MultipartFile[] newHallImages); - String updateHallImage(Integer hallImageId, MultipartFile hallImage) throws IOException; + HallDetails saveHallDetails(HallDetails hallDetails, List hallImages); + + HallDetails getHallById(int hallId); + + HallDetails deActivateHallById(int hallId); + + HallDetails saveHallByAdmin( + String hallName, + float depositAmount, + float halfDayAmt, float fullDayAmt, + float gst, float hallArea, String ebNumber, float ebCostPerUnit, + String parkingCapacity, int seatingCapacity, + String doorNo, String street, + String area, String zone, + String division, String landMark, + String city, + int pinCode, String latitude, + String longitude, String hallInchargeName, + long hallInchargeNo, + String updatedId, + MultipartFile hallImages[], float halfDepositAmt); + + /** HQ-specific overload that also persists floor details. */ + HallDetails saveHallByHQ( + String hallName, + float depositAmount, + float halfDayAmt, float fullDayAmt, + float gst, float hallArea, String ebNumber, float ebCostPerUnit, + String parkingCapacity, int seatingCapacity, + String doorNo, String street, + String area, String zone, + String division, String landMark, + String city, + int pinCode, String latitude, + String longitude, String hallInchargeName, + long hallInchargeNo, + String updatedId, + MultipartFile[] hallImages, float halfDepositAmt, + List floorNames, List floorCapacities); + + /** Replaces floor details for an existing hall (delete-and-re-insert). */ + void updateFloorDetails(int hallId, List floorNames, List floorCapacities); + + List getHallImages(int hallId); + + String updateHallDetail(HallDetails hallDetails, List images); + + List removeHallById(HashSet hallIds); + + List getHallNames(); + + void saveHallImage(Long hallId, MultipartFile file) throws IOException; + + List getHallImagesByHallId(Long hallId); + + List getHallNamesbyzone(String zone); + + public Map getHallsDetailsByZone(String zone); + + // officerDashboard + public Map getHallsDetailsForOfficer(String zone); + + void updatenewHallImages(Integer hallId, MultipartFile[] newHallImages); + + String updateHallImage(Integer hallImageId, MultipartFile hallImage) throws IOException; } 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 861dd04e..96a15c90 100644 --- a/src/main/java/com/gcc/communityHall/service/Impl/BookingServiceImpl.java +++ b/src/main/java/com/gcc/communityHall/service/Impl/BookingServiceImpl.java @@ -1869,8 +1869,8 @@ public class BookingServiceImpl implements BookingService { // sreeja @Override - public List getPastData(int hall_id) { - List data = bookingCalendarRepository.getPastData(hall_id); + public List> getPastData(int hall_id) { + List> data = bookingCalendarRepository.getPastData(hall_id); return data; } @@ -2360,6 +2360,12 @@ public class BookingServiceImpl implements BookingService { String reasonforblocking, List selectedBookings, String updatedBy, String[] descriptions, MultipartFile[] documents) { if (selectedBookings != null && !selectedBookings.isEmpty()) { + + // ── Collect cancelled user booking IDs (used later to build ONE GCC record) ── + List cancelledBookingIds = new ArrayList<>(); + + // ── Phase 1: Cancel each selected booking (BookingDetails + BookingCalendar + // slots) ── for (String bookingIdStr : selectedBookings) { Integer bookingId = Integer.parseInt(bookingIdStr); Optional optionalBooking = bookingDetailsRepository.findById(bookingId); @@ -2387,102 +2393,10 @@ public class BookingServiceImpl implements BookingService { updateBookingStatus(bb); } - // GCC blocking entry - GccBlockingDate gcc = new GccBlockingDate(); - gcc.setStartDate(convertStringToDate(fromDate)); - gcc.setEndDate(convertStringToDate(toDate)); - gcc.setHallId(String.join(",", - hallIdsList.stream().map(String::valueOf).collect(Collectors.toList()))); - gcc.setUpdatedBy(updatedBy); - gcc.setCdate(new Date()); - gcc.setBlockingReason(reasonforblocking); - if (documents != null && documents.length > 0 && descriptions != null - && descriptions.length > 0) { - int i = 0; - for (MultipartFile document : documents) { - String filePath = uploadDirectory + "/" + gcc.getBlockingId() + "_" + i + "_" - + document.getOriginalFilename(); - String documentUrl = serverPath + "gccblockingdocs/" + gcc.getBlockingId() + "_" + i - + "_" + document.getOriginalFilename(); - - try (FileOutputStream fos = new FileOutputStream(filePath)) { - // Save document to the file system - byte[] bytes = document.getBytes(); - fos.write(bytes); - - // Save document details along with description in the database - GccblockingDocuments documentDetails = new GccblockingDocuments(); // Assuming you - // have a - // DocumentDetails - // entity - documentDetails.setBlockingDate(gcc); // Assuming hallDetails is associated with the - // document - documentDetails.setBlockingDocument(documentUrl); // Save the URL of the uploaded - // document - documentDetails.setDescription(descriptions[i]); // Save corresponding description - gccblockingDocumentsRepo.save(documentDetails); // Save the document and description - // in the database - } catch (IOException e) { - throw new RuntimeException("Failed to save document", e); - } - i++; - } - } - - // GCC blocking History - GccBlockingHistory gccblockinghistory = new GccBlockingHistory(); - gccblockinghistory.setStartDate(convertStringToDate(fromDate)); - gccblockinghistory.setEndDate(convertStringToDate(toDate)); - gccblockinghistory.setHallId(String.join(",", - hallIdsList.stream().map(String::valueOf).collect(Collectors.toList()))); - gccblockinghistory.setUpdatedBy(updatedBy); - gccblockinghistory.setCdate(new Date()); - gccblockinghistory.setBlockingReason(reasonforblocking); - List bookingIds = saveGCCBlockingDate(gcc); - gccblockinghistory.setBookingIds(bookingIds.toString()); - blockingHistoryRepository.save(gccblockinghistory); - // GCC calendar - for (Long hallId : hallIdsList) { - LocalDate fDate = LocalDate.parse(fromDate); - LocalDate tDate = LocalDate.parse(toDate); - - List dates = getDateRange(fDate, tDate); - - for (LocalDate aa : dates) { - String uniqueId = aa.format(DateTimeFormatter.ofPattern("yyyyMMdd")) + hallId; - BookingCalendar data = getbyDates(aa, hallId.toString()); - int userbookingbookingId = bookingIds.get(hallIdsList.indexOf(hallId)); - if (data != null) { - System.out.println("uniqueId...1" + uniqueId); - data.setBookingId_1(String.valueOf(userbookingbookingId)); - data.setBookingId_2(String.valueOf(userbookingbookingId)); - data.setMorningSlot(true); - data.setEveningSlot(true); - data.setIs_blocked(true); - data.setUnique_id(uniqueId); - updateBookingStatus(data); - } else { - System.out.println("uniqueId...2" + uniqueId); - BookingCalendar book = new BookingCalendar(); - book.setBdate(aa); - book.setBookingId_1(String.valueOf(userbookingbookingId)); - book.setBookingId_2(String.valueOf(userbookingbookingId)); - book.setMorningSlot(true); - book.setEveningSlot(true); - book.setHallId(hallId.intValue()); - book.setIs_active(true); - book.setIs_booked(2); - book.setIs_delete(false); - book.setIs_blocked(true); - book.setUnique_id(uniqueId); - updateBookingStatus(book); - } - } - } - - updateBookingStatusById(booking.getBookingId(), booking.getBookingStatus().GCC_BLOCKED, + updateBookingStatusById(booking.getBookingId(), BookingStatus.GCC_BLOCKED, reasonforblocking); - // whatsup msg and SMS + + // WhatsApp msg and SMS String gccblockedsms = "Your booking ID " + bookingId + " on " + booking.getStartDate() + " has been blocked by GCC due to " + reasonforblocking + ". The entire amount paid will be refunded to your account with in 3 to 15 days."; @@ -2499,6 +2413,105 @@ public class BookingServiceImpl implements BookingService { whatsappMsgServiceImpl.sendMsg(gccblockedwhatsupmsg); whatsappMsgServiceImpl.sendSMS(gccblockedurlString); bookingDetailsRepository.save(booking); + + cancelledBookingIds.add(bookingId); + } + } + } + + // ── Phase 2: Create ONE GccBlockingDate record for the entire operation ── + GccBlockingDate gcc = new GccBlockingDate(); + gcc.setStartDate(convertStringToDate(fromDate)); + gcc.setEndDate(convertStringToDate(toDate)); + gcc.setHallId(String.join(",", + hallIdsList.stream().map(String::valueOf).collect(Collectors.toList()))); + gcc.setUpdatedBy(updatedBy); + gcc.setCdate(new Date()); + gcc.setBlockingReason(reasonforblocking); + + // Save document(s) if present + if (documents != null && documents.length > 0 && descriptions != null + && descriptions.length > 0) { + int i = 0; + for (MultipartFile document : documents) { + String filePath = uploadDirectory + "/" + gcc.getBlockingId() + "_" + i + "_" + + document.getOriginalFilename(); + String documentUrl = serverPath + "gccblockingdocs/" + gcc.getBlockingId() + "_" + i + + "_" + document.getOriginalFilename(); + try (FileOutputStream fos = new FileOutputStream(filePath)) { + byte[] bytes = document.getBytes(); + fos.write(bytes); + GccblockingDocuments documentDetails = new GccblockingDocuments(); + documentDetails.setBlockingDate(gcc); + documentDetails.setBlockingDocument(documentUrl); + documentDetails.setDescription(descriptions[i]); + gccblockingDocumentsRepo.save(documentDetails); + } catch (IOException e) { + throw new RuntimeException("Failed to save document", e); + } + i++; + } + } + + // Save the single GCC blocking record + List gccBookingIds = saveGCCBlockingDate(gcc); + + // Store the actual cancelled user booking IDs on the gcc record + if (!cancelledBookingIds.isEmpty()) { + String cancelledIdsStr = cancelledBookingIds.stream() + .map(String::valueOf) + .collect(Collectors.joining(",")); + gcc.setBookingIds(cancelledIdsStr); + gccBlockingDateRepository.save(gcc); + } + + // GCC Blocking History — one entry for the whole operation + GccBlockingHistory gccblockinghistory = new GccBlockingHistory(); + gccblockinghistory.setStartDate(convertStringToDate(fromDate)); + gccblockinghistory.setEndDate(convertStringToDate(toDate)); + gccblockinghistory.setHallId(String.join(",", + hallIdsList.stream().map(String::valueOf).collect(Collectors.toList()))); + gccblockinghistory.setUpdatedBy(updatedBy); + gccblockinghistory.setCdate(new Date()); + gccblockinghistory.setBlockingReason(reasonforblocking); + gccblockinghistory.setBookingIds(cancelledBookingIds.stream() + .map(String::valueOf).collect(Collectors.joining(","))); + blockingHistoryRepository.save(gccblockinghistory); + + // ── Phase 3: Update BookingCalendar (mark dates as GCC-blocked) ── + for (Long hallId : hallIdsList) { + LocalDate fDate = LocalDate.parse(fromDate); + LocalDate tDate = LocalDate.parse(toDate); + List dates = getDateRange(fDate, tDate); + + for (LocalDate aa : dates) { + String uniqueId = aa.format(DateTimeFormatter.ofPattern("yyyyMMdd")) + hallId; + BookingCalendar data = getbyDates(aa, hallId.toString()); + int userbookingbookingId = gccBookingIds.get(hallIdsList.indexOf(hallId)); + if (data != null) { + System.out.println("uniqueId...1" + uniqueId); + data.setBookingId_1(String.valueOf(userbookingbookingId)); + data.setBookingId_2(String.valueOf(userbookingbookingId)); + data.setMorningSlot(true); + data.setEveningSlot(true); + data.setIs_blocked(true); + data.setUnique_id(uniqueId); + updateBookingStatus(data); + } else { + System.out.println("uniqueId...2" + uniqueId); + BookingCalendar book = new BookingCalendar(); + book.setBdate(aa); + book.setBookingId_1(String.valueOf(userbookingbookingId)); + book.setBookingId_2(String.valueOf(userbookingbookingId)); + book.setMorningSlot(true); + book.setEveningSlot(true); + book.setHallId(hallId.intValue()); + book.setIs_active(true); + book.setIs_booked(2); + book.setIs_delete(false); + book.setIs_blocked(true); + book.setUnique_id(uniqueId); + updateBookingStatus(book); } } } @@ -2559,17 +2572,19 @@ public class BookingServiceImpl implements BookingService { List dates = getDateRange(fDate, tDate); for (LocalDate date : dates) { + // BookingDetails bookingData = + // bookingDetailsRepository.findByHallIdAndDate(date, hallId.intValue()); BookingCalendar data = getbyDates(date, hallId.toString()); String uniqueId = date.format(DateTimeFormatter.ofPattern("yyyyMMdd")) + hallId; int userbookingbookingId = bookingIds.get(hallIdsList.indexOf(hallId)); if (data != null) { System.out.println("uniqueId...11" + uniqueId); - data.setBookingId_1(String.valueOf(userbookingbookingId)); - data.setBookingId_2(String.valueOf(userbookingbookingId)); - data.setMorningSlot(true); - data.setEveningSlot(true); + // data.setBookingId_1(String.valueOf(userbookingbookingId)); + // data.setBookingId_2(String.valueOf(userbookingbookingId)); + // data.setMorningSlot(true); + // data.setEveningSlot(true); data.setIs_blocked(true); - data.setUnique_id(uniqueId); + // data.setUnique_id(uniqueId); updateBookingStatus(data); } else { System.out.println("uniqueId...21" + uniqueId); @@ -2638,6 +2653,7 @@ public class BookingServiceImpl implements BookingService { String key = entry.get("key") != null ? (String) entry.get("key") : "total"; Integer totalCount = entry.get("totalCount") != null ? ((Number) entry.get("totalCount")).intValue() : 0; + // transformedData.putIfAbsent(category, new HashMap<>()); transformedData.get(category).put(key, totalCount); @@ -2664,6 +2680,7 @@ public class BookingServiceImpl implements BookingService { : 0; Integer futurebooking = entry.get("FUTURE_Events") != null ? ((Number) entry.get("FUTURE_Events")).intValue() + // : 0; transformedData.get(category).put("PAST_Events", pastbooking); transformedData.get(category).put("FUTURE_Events", futurebooking); @@ -2710,9 +2727,13 @@ public class BookingServiceImpl implements BookingService { Integer mainRefundedAmount = entry.get("main_refunded_amount") != null ? ((Number) entry.get("main_refunded_amount")).intValue() : 0; + Integer mainGstAmount = entry.get("main_gst_amount") != null + ? ((Number) entry.get("main_gst_amount")).intValue() + : 0; transformedData.get(category).put("main_total_amount", mainTotalAmount); transformedData.get(category).put("main_net_amount", mainNetAmount); transformedData.get(category).put("main_refunded_amount", mainRefundedAmount); + transformedData.get(category).put("main_gst_amount", mainGstAmount); } if (category.equals("past_future")) { Integer pastbooking = entry.get("PAST_Events") != null ? ((Number) entry.get("PAST_Events")).intValue() @@ -2726,6 +2747,7 @@ public class BookingServiceImpl implements BookingService { } return transformedData; + } @Override @@ -3078,4 +3100,128 @@ public class BookingServiceImpl implements BookingService { return bookingDetailsRepository.getCounterWiseBookingList(fromDate, toDate); } + @Override + public List getBlockedEvents() { + return blockingDateRepository.findAllBlocked(); + } + + @Override + @Transactional + public void blockWithoutCancellingBookings(String fromDate, String toDate, List hallIdsList, + String reasonforblocking, String updatedBy, String[] descriptions, MultipartFile[] documents) { + + // 1. Create and save the GccBlockingDate record + GccBlockingDate gcc = new GccBlockingDate(); + gcc.setStartDate(convertStringToDate(fromDate)); + gcc.setEndDate(convertStringToDate(toDate)); + gcc.setHallId(String.join(",", hallIdsList.stream().map(String::valueOf).collect(Collectors.toList()))); + gcc.setUpdatedBy(updatedBy); + gcc.setCdate(new Date()); + gcc.setBlockingReason(reasonforblocking); + + // 2. Save documents if provided + GccBlockingDate savedGcc = gccBlockingDateRepository.save(gcc); + if (documents != null && documents.length > 0 && descriptions != null + && descriptions.length == documents.length) { + for (int i = 0; i < documents.length; i++) { + MultipartFile document = documents[i]; + String filePath = uploadDirectory + "/" + savedGcc.getBlockingId() + "_" + i + "_" + + document.getOriginalFilename(); + String documentUrl = serverPath + "gccblockingdocs/" + savedGcc.getBlockingId() + "_" + i + "_" + + document.getOriginalFilename(); + try (FileOutputStream fos = new FileOutputStream(filePath)) { + fos.write(document.getBytes()); + GccblockingDocuments documentDetails = new GccblockingDocuments(); + documentDetails.setBlockingDate(savedGcc); + documentDetails.setBlockingDocument(documentUrl); + documentDetails.setDescription(descriptions[i]); + gccblockingDocumentsRepo.save(documentDetails); + } catch (IOException e) { + throw new RuntimeException("Failed to save document: " + document.getOriginalFilename(), e); + } + } + } + + // 3. Save GccBlockingDate entry for each hall (one booking_details row per + // hall) + // Reuse saveGCCBlockingDate so bookingIds are stored on the gcc record + List bookingIds = saveGCCBlockingDate(gcc); + + // 4. Save GccBlockingHistory + GccBlockingHistory gccblockinghistory = new GccBlockingHistory(); + gccblockinghistory.setStartDate(convertStringToDate(fromDate)); + gccblockinghistory.setEndDate(convertStringToDate(toDate)); + gccblockinghistory + .setHallId(String.join(",", hallIdsList.stream().map(String::valueOf).collect(Collectors.toList()))); + gccblockinghistory.setUpdatedBy(updatedBy); + gccblockinghistory.setCdate(new Date()); + gccblockinghistory.setBlockingReason(reasonforblocking); + gccblockinghistory.setBookingIds(bookingIds.stream().map(String::valueOf).collect(Collectors.joining(","))); + blockingHistoryRepository.save(gccblockinghistory); + + // 5. Iterate over each hall and each date — smart blocking per slot + for (Long hallId : hallIdsList) { + LocalDate fDate = LocalDate.parse(fromDate); + LocalDate tDate = LocalDate.parse(toDate); + List dates = getDateRange(fDate, tDate); + + int gccBookingId = bookingIds.get(hallIdsList.indexOf(hallId)); + + for (LocalDate date : dates) { + String uniqueId = date.format(DateTimeFormatter.ofPattern("yyyyMMdd")) + hallId; + + // Check whether an APPROVED user booking already exists for this hall on this + // date + List approvedBookings = bookingDetailsRepository.findByHallIdAndDate(date, + hallId.intValue()); + + BookingCalendar calRow = getbyDates(date, hallId.toString()); + + if (!approvedBookings.isEmpty()) { + // ── APPROVED booking exists: only flag as blocked, leave slots intact ── + if (calRow != null) { + calRow.setIs_blocked(true); + updateBookingStatus(calRow); + } else { + // Defensive: calendar row missing for an approved booking — create minimal row + BookingCalendar minRow = new BookingCalendar(); + minRow.setBdate(date); + minRow.setHallId(hallId.intValue()); + minRow.setIs_blocked(true); + minRow.setIs_active(true); + minRow.setIs_booked(0); + minRow.setIs_delete(false); + minRow.setUnique_id(uniqueId); + updateBookingStatus(minRow); + } + } else { + // ── No APPROVED booking: GCC takes full slot ownership ── + if (calRow != null) { + calRow.setBookingId_1(String.valueOf(gccBookingId)); + calRow.setBookingId_2(String.valueOf(gccBookingId)); + calRow.setMorningSlot(true); + calRow.setEveningSlot(true); + calRow.setIs_blocked(true); + calRow.setUnique_id(uniqueId); + updateBookingStatus(calRow); + } else { + BookingCalendar book = new BookingCalendar(); + book.setBdate(date); + book.setBookingId_1(String.valueOf(gccBookingId)); + book.setBookingId_2(String.valueOf(gccBookingId)); + book.setMorningSlot(true); + book.setEveningSlot(true); + book.setHallId(hallId.intValue()); + book.setIs_active(true); + book.setIs_booked(2); + book.setIs_delete(false); + book.setIs_blocked(true); + book.setUnique_id(uniqueId); + updateBookingStatus(book); + } + } + } + } + } + } diff --git a/src/main/java/com/gcc/communityHall/service/Impl/HallDetailServiceImpl.java b/src/main/java/com/gcc/communityHall/service/Impl/HallDetailServiceImpl.java index 07e87e5a..a37058d7 100644 --- a/src/main/java/com/gcc/communityHall/service/Impl/HallDetailServiceImpl.java +++ b/src/main/java/com/gcc/communityHall/service/Impl/HallDetailServiceImpl.java @@ -16,10 +16,13 @@ import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; +import com.gcc.communityHall.entity.FloorDetails; import com.gcc.communityHall.entity.HallDetails; import com.gcc.communityHall.entity.HallImages; +import com.gcc.communityHall.repository.FloorDetailsRepository; import com.gcc.communityHall.repository.HallDetailsRepository; import com.gcc.communityHall.repository.HallImagesRepository; import com.gcc.communityHall.service.HallDetailService; @@ -27,21 +30,28 @@ import com.gcc.communityHall.service.HallDetailService; @Service public class HallDetailServiceImpl implements HallDetailService { -// @Autowired + // @Autowired private HallDetailsRepository hallDetailsRepository; private HallImagesRepository hallImagesRepository; private final String hallDirectory; private final String hallImageUrl; + + @Autowired + private FloorDetailsRepository floorDetailsRepository; + @Autowired - HallDetailServiceImpl(HallDetailsRepository hallDetailsRepository, HallImagesRepository hallImagesRepository, @Value("${file.hall.upload.directory}") String hallDirectory, @Value("${file.hall.fullpath}") String hallImageUrl){ - this.hallDetailsRepository=hallDetailsRepository; - this.hallDirectory=hallDirectory; - this.hallImageUrl=hallImageUrl; + HallDetailServiceImpl(HallDetailsRepository hallDetailsRepository, HallImagesRepository hallImagesRepository, + @Value("${file.hall.upload.directory}") String hallDirectory, + @Value("${file.hall.fullpath}") String hallImageUrl) { + this.hallDetailsRepository = hallDetailsRepository; + this.hallDirectory = hallDirectory; + this.hallImageUrl = hallImageUrl; this.hallImagesRepository = hallImagesRepository; } + @Override public HallDetails saveHallDetails(HallDetails hallDetails, List hallImages) { - if(hallImages.size()>0){ + if (hallImages.size() > 0) { } return null; @@ -50,7 +60,7 @@ public class HallDetailServiceImpl implements HallDetailService { @Override public HallDetails getHallById(int hallId) { Optional hallDetails = hallDetailsRepository.findById(hallId); - if(hallDetails.isPresent()){ + if (hallDetails.isPresent()) { return hallDetails.get(); } @@ -63,14 +73,14 @@ public class HallDetailServiceImpl implements HallDetailService { } @Override - public HallDetails saveHall( - String hallName,float depositAmount, float halfDayAmt, - float fullDayAmt, float gst,float hallArea, String ebNumber, float ebCostPerUnit, - int parkingCapacity, int seatingCapacity, - String doorNo, String street, String area, String zone, - String division, String landMark, String city, int pinCode, - String latitude, String longitude, String hallInchargeName, - long hallInchargeNo,String updatedId, MultipartFile[] hallImages, float halfDepositAmt) { + public HallDetails saveHallByAdmin( + String hallName, float depositAmount, float halfDayAmt, + float fullDayAmt, float gst, float hallArea, String ebNumber, float ebCostPerUnit, + String parkingCapacity, int seatingCapacity, + String doorNo, String street, String area, String zone, + String division, String landMark, String city, int pinCode, + String latitude, String longitude, String hallInchargeName, + long hallInchargeNo, String updatedId, MultipartFile[] hallImages, float halfDepositAmt) { HallDetails hall = new HallDetails(); hall.setHallName(hallName); hall.setDoorNo(doorNo); @@ -81,7 +91,7 @@ public class HallDetailServiceImpl implements HallDetailService { hall.setPinCode(pinCode); hall.setDivision(division); hall.setZone(zone); - hall.setEbNumber(ebNumber); + hall.setEbNumber(ebNumber); hall.setEbCostPerUnit(ebCostPerUnit); hall.setFullDayRent(fullDayAmt); hall.setHalfDayRent(halfDayAmt); @@ -98,18 +108,22 @@ public class HallDetailServiceImpl implements HallDetailService { hall.setCreateddate(LocalDate.now()); hall.setHalfDepositAmount(halfDepositAmt); HallDetails hallDetails = hallDetailsRepository.save(hall); - if(hallImages!=null && hallImages.length>0){ - int i=0; + if (hallImages != null && hallImages.length > 0) { + int i = 0; for (MultipartFile hallImage : hallImages) { HallImages hallImages1 = new HallImages(); - String filePath = hallDirectory+"/"+hallDetails.getHallId()+ "_"+i+"_" + hallImage.getOriginalFilename(); - String imageUrl = hallImageUrl+"hallImages/"+hallDetails.getHallId()+ "_"+i+"_" + hallImage.getOriginalFilename(); - try(FileOutputStream fos = new FileOutputStream(filePath)){ - byte [] bytes = hallImage.getBytes(); + String filePath = hallDirectory + "/" + hallDetails.getHallId() + "_" + i + + "_" + + hallImage.getOriginalFilename(); + String imageUrl = hallImageUrl + "hallImages/" + hallDetails.getHallId() + + "_" + i + "_" + + hallImage.getOriginalFilename(); + try (FileOutputStream fos = new FileOutputStream(filePath)) { + byte[] bytes = hallImage.getBytes(); fos.write(bytes); hallImages1.setHallDetails(hallDetails); hallImages1.setHallImage(imageUrl); // hall/imagename.jpg - hallImagesRepository.save(hallImages1); + hallImagesRepository.save(hallImages1); } catch (IOException e) { throw new RuntimeException(e); } @@ -118,17 +132,105 @@ public class HallDetailServiceImpl implements HallDetailService { } return null; } + + /** + * HQ-specific overload: saves hall details + floor details in one call. + */ + @Override + public HallDetails saveHallByHQ( + String hallName, float depositAmount, float halfDayAmt, + float fullDayAmt, float gst, float hallArea, String ebNumber, float ebCostPerUnit, + String parkingCapacity, int seatingCapacity, + String doorNo, String street, String area, String zone, + String division, String landMark, String city, int pinCode, + String latitude, String longitude, String hallInchargeName, + long hallInchargeNo, String updatedId, MultipartFile[] hallImages, float halfDepositAmt, + List floorNames, List floorCapacities) { + + // Reuse the existing saveHall to persist the hall + images + saveHallByAdmin(hallName, depositAmount, halfDayAmt, fullDayAmt, gst, hallArea, + ebNumber, ebCostPerUnit, parkingCapacity, seatingCapacity, + doorNo, street, area, zone, division, landMark, city, pinCode, + latitude, longitude, hallInchargeName, hallInchargeNo, + updatedId, hallImages, halfDepositAmt); + + // Fetch the just-saved hall to get its generated ID + // (the hall is the most recently inserted one with this name) + HallDetails savedHall = hallDetailsRepository + .findAll() + .stream() + .filter(h -> hallName.equals(h.getHallName())) + .reduce((first, second) -> second) // last inserted + .orElse(null); + + if (savedHall != null && floorNames != null && !floorNames.isEmpty()) { + for (int i = 0; i < floorNames.size(); i++) { + String fname = floorNames.get(i); + if (fname == null || fname.trim().isEmpty()) + continue; + double fcap = (floorCapacities != null && i < floorCapacities.size() && floorCapacities.get(i) != null) + ? floorCapacities.get(i) + : 0.0; + FloorDetails fd = new FloorDetails(); + fd.setFloor(fname.trim()); + fd.setHallarea(fcap); + fd.setHallDetails(savedHall); + fd.setActive(true); + fd.setDelete(false); + floorDetailsRepository.save(fd); + } + } + return savedHall; + } + + /** + * Soft-deletes existing active floor rows, then inserts new floor records. + * Existing rows get: is_active = false, is_delete = true. + * New rows get: is_active = true, is_delete = false. + */ + @Override + @Transactional + public void updateFloorDetails(int hallId, List floorNames, List floorCapacities) { + // Soft-delete all currently active floor rows for this hall + floorDetailsRepository.softDeleteByHallId(hallId); + + HallDetails hall = hallDetailsRepository.findById(hallId).orElse(null); + if (hall == null) + return; + if (floorNames == null || floorNames.isEmpty()) + return; + + // Insert new floor records + for (int i = 0; i < floorNames.size(); i++) { + String fname = floorNames.get(i); + if (fname == null || fname.trim().isEmpty()) + continue; + double fcap = (floorCapacities != null && i < floorCapacities.size() && floorCapacities.get(i) != null) + ? floorCapacities.get(i) + : 0.0; + FloorDetails fd = new FloorDetails(); + fd.setFloor(fname.trim()); + fd.setHallarea(fcap); + fd.setHallDetails(hall); + fd.setActive(true); + fd.setDelete(false); + floorDetailsRepository.save(fd); + } + } + public void updatenewHallImages(Integer hallId, MultipartFile[] newHallImages) { // Fetch the existing hall details from the database HallDetails hallDetails = hallDetailsRepository.findById(hallId) .orElseThrow(() -> new RuntimeException("Hall not found with id: " + hallId)); if (newHallImages != null && newHallImages.length > 0) { - int i = hallDetails.getHallImagesList().size(); // Start index after existing images + int i = hallDetails.getHallImagesList().size(); // Start index after existing images for (MultipartFile hallImage : newHallImages) { HallImages hallImageEntity = new HallImages(); - String filePath = hallDirectory + "/" + hallDetails.getHallId() + "_" + i + "_" + hallImage.getOriginalFilename(); - String imageUrl = hallImageUrl + "hallImages/" + hallDetails.getHallId() + "_" + i + "_" + hallImage.getOriginalFilename(); + String filePath = hallDirectory + "/" + hallDetails.getHallId() + "_" + i + "_" + + hallImage.getOriginalFilename(); + String imageUrl = hallImageUrl + "hallImages/" + hallDetails.getHallId() + "_" + i + "_" + + hallImage.getOriginalFilename(); try (FileOutputStream fos = new FileOutputStream(filePath)) { byte[] bytes = hallImage.getBytes(); @@ -145,6 +247,7 @@ public class HallDetailServiceImpl implements HallDetailService { } } } + public String updateHallImage(Integer hallImageId, MultipartFile hallImage) throws IOException { Optional optionalHallImage = hallImagesRepository.findById(hallImageId); if (optionalHallImage.isPresent()) { @@ -168,16 +271,16 @@ public class HallDetailServiceImpl implements HallDetailService { } } - @Override - public List getHallImages(int hallId) { - // TODO Auto-generated method stub - HallDetails hall = new HallDetails(); - hall.setHallId(hallId); + @Override + public List getHallImages(int hallId) { + // TODO Auto-generated method stub + HallDetails hall = new HallDetails(); + hall.setHallId(hallId); + + return hallImagesRepository.findByHallDetails(hall); + } - return hallImagesRepository.findByHallDetails(hall); - } - - @Override + @Override public String updateHallDetail(HallDetails hallDetails, List images) { HallDetails existingHall = hallDetailsRepository.findById(hallDetails.getHallId()).orElse(null); @@ -204,7 +307,7 @@ public class HallDetailServiceImpl implements HallDetailService { existingHall.setSeatingCapacity(hallDetails.getSeatingCapacity()); existingHall.setGst(hallDetails.getGst()); existingHall.setEbCostPerUnit(hallDetails.getEbCostPerUnit()); - existingHall.setActive(hallDetails.isActive()); + existingHall.setActive(hallDetails.isActive()); existingHall.setEbNumber(hallDetails.getEbNumber()); // Update images @@ -215,13 +318,15 @@ public class HallDetailServiceImpl implements HallDetailService { } else { hallImagesList.clear(); // Clear existing images } - int i=0; + int i = 0; for (MultipartFile image : images) { HallImages hallImage = new HallImages(); try { // Save image to storage location - String filePath = hallDirectory + "/" + existingHall.getHallId() + "_"+i+"_" + image.getOriginalFilename(); - String imageUrl = hallImageUrl + "hall/" + existingHall.getHallId() + "_" +i+"_"+ image.getOriginalFilename(); + String filePath = hallDirectory + "/" + existingHall.getHallId() + "_" + i + "_" + + image.getOriginalFilename(); + String imageUrl = hallImageUrl + "hall/" + existingHall.getHallId() + "_" + i + "_" + + image.getOriginalFilename(); try (FileOutputStream fos = new FileOutputStream(filePath)) { byte[] bytes = image.getBytes(); fos.write(bytes); @@ -243,26 +348,28 @@ public class HallDetailServiceImpl implements HallDetailService { } return "failed"; } - + @Override public List removeHallById(HashSet hallIds) { - if(hallIds.isEmpty()){ + if (hallIds.isEmpty()) { hallIds.add(0); } - //System.out.println(hallIds); + // System.out.println(hallIds); return hallDetailsRepository.removeHallById(hallIds); } + public List getHallNames() { List halls = hallDetailsRepository.findAll(); return halls.stream() - .map(hall -> { - HallDetails hallDetails = new HallDetails(); - hallDetails.setHallId(hall.getHallId()); - hallDetails.setHallName(hall.getHallName()); - return hallDetails; - }) - .collect(Collectors.toList()); + .map(hall -> { + HallDetails hallDetails = new HallDetails(); + hallDetails.setHallId(hall.getHallId()); + hallDetails.setHallName(hall.getHallName()); + return hallDetails; + }) + .collect(Collectors.toList()); } + @Override public void saveHallImage(Long hallId, MultipartFile file) throws IOException { try { @@ -270,7 +377,8 @@ public class HallDetailServiceImpl implements HallDetailService { .orElseThrow(() -> new IllegalArgumentException("Invalid hall ID")); HallImages hallImage = new HallImages(); - hallImage.setHallImage(Arrays.toString(file.getBytes())); // Check if this line needs adjustment based on file handling + hallImage.setHallImage(Arrays.toString(file.getBytes())); // Check if this line needs adjustment based on + // file handling hallImage.setHallDetails(hallDetails); hallImagesRepository.save(hallImage); } catch (Exception e) { @@ -279,25 +387,25 @@ public class HallDetailServiceImpl implements HallDetailService { } } - @Override public List getHallImagesByHallId(Long hallId) { return hallImagesRepository.findByHallDetails_HallId(hallId); } - @Override - public List getHallNamesbyzone(String zone) { - List halls = hallDetailsRepository.findByZone(zone); + + @Override + public List getHallNamesbyzone(String zone) { + List halls = hallDetailsRepository.findByZone(zone); return halls.stream() - .map(hall -> { - HallDetails hallDetails = new HallDetails(); - hallDetails.setHallId(hall.getHallId()); - hallDetails.setHallName(hall.getHallName()); - return hallDetails; - }) - .collect(Collectors.toList()); - } - - @Override + .map(hall -> { + HallDetails hallDetails = new HallDetails(); + hallDetails.setHallId(hall.getHallId()); + hallDetails.setHallName(hall.getHallName()); + return hallDetails; + }) + .collect(Collectors.toList()); + } + + @Override public Map getHallsDetailsByZone(String zone) { // Get the total bookings and amount received by zone Map halldetails = hallDetailsRepository.getTotalBookingsAndAmountReceivedByZone(zone); @@ -313,22 +421,22 @@ public class HallDetailServiceImpl implements HallDetailService { return modifiableHalldetails; } - - //officer dashboard - @Override - public Map getHallsDetailsForOfficer(String zone) { - // Get the total bookings and amount received by zone - Map halldetails = hallDetailsRepository.getTotalCountsForOfficer(zone); - // Create a new modifiable map and copy values from the unmodifiable map - Map modifiableHalldetails = new HashMap<>(halldetails); + // officer dashboard + @Override + public Map getHallsDetailsForOfficer(String zone) { + // Get the total bookings and amount received by zone + Map halldetails = hallDetailsRepository.getTotalCountsForOfficer(zone); + + // Create a new modifiable map and copy values from the unmodifiable map + Map modifiableHalldetails = new HashMap<>(halldetails); - // Get the details of each hall in the zone - List> zonehalls = hallDetailsRepository.getHallCountsForOfficer(zone); + // Get the details of each hall in the zone + List> zonehalls = hallDetailsRepository.getHallCountsForOfficer(zone); - // Add the list of hall details to the new modifiable map - modifiableHalldetails.put("zonehalls", zonehalls); + // Add the list of hall details to the new modifiable map + modifiableHalldetails.put("zonehalls", zonehalls); - return modifiableHalldetails; - } + return modifiableHalldetails; + } } diff --git a/src/main/resources/paymentConfig.properties b/src/main/resources/paymentConfig.properties index a1a4e5b1..c066969b 100644 --- a/src/main/resources/paymentConfig.properties +++ b/src/main/resources/paymentConfig.properties @@ -6,7 +6,7 @@ #payment.worldline.transactionSuccessCode=0300 #payment.worldline.refundSuccessCode=0400 -payment.worldline.merchantId=T1037717 +payment.worldline.merchantId=L1037717 payment.worldline.encryptionKey=6207149300MFLGNY payment.worldline.encryptionIV=3422107798TKQCNG payment.worldline.schemeCode=FIRST diff --git a/src/main/resources/templates/admin/developer.html b/src/main/resources/templates/admin/developer.html index dfcfb9fa..a7776b89 100644 --- a/src/main/resources/templates/admin/developer.html +++ b/src/main/resources/templates/admin/developer.html @@ -55,197 +55,198 @@ - - -
- - - - - - - - - - - - - - - - - - - - - - - - -
S.NoBooking IdBooking DateRefund StatusAmountTransaction IdUser Id
0
-
-
- - - - - - - - - - - - - - - - - - - - - - - - - - -
S.NoBooking DateBooking Id1Booking Id2Morning SlotEvening SlotHall NameHall Id
0
+ +
+ - - -
- - - -
- - + + \ No newline at end of file diff --git a/src/main/resources/templates/admin/gccblocking-new.html b/src/main/resources/templates/admin/gccblocking-new.html new file mode 100644 index 00000000..23c969e8 --- /dev/null +++ b/src/main/resources/templates/admin/gccblocking-new.html @@ -0,0 +1,1033 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/templates/admin/halldetailslist.html b/src/main/resources/templates/admin/halldetailslist.html index 561062e9..b84b9767 100644 --- a/src/main/resources/templates/admin/halldetailslist.html +++ b/src/main/resources/templates/admin/halldetailslist.html @@ -4,864 +4,833 @@ - - - - -