diff --git a/src/main/java/com/gcc/communityHall/controller/AdminAPIController.java b/src/main/java/com/gcc/communityHall/controller/AdminAPIController.java index e152ab27..8b385d74 100644 --- a/src/main/java/com/gcc/communityHall/controller/AdminAPIController.java +++ b/src/main/java/com/gcc/communityHall/controller/AdminAPIController.java @@ -1486,7 +1486,6 @@ public class AdminAPIController { } } - @PostMapping("/uploadnoc") public ResponseEntity uploadnoc(@RequestParam("nocFile") MultipartFile file, @RequestParam("bookingid") int bookingId) { diff --git a/src/main/java/com/gcc/communityHall/controller/Admincontroller.java b/src/main/java/com/gcc/communityHall/controller/Admincontroller.java index edf6bc3b..3c2607e3 100644 --- a/src/main/java/com/gcc/communityHall/controller/Admincontroller.java +++ b/src/main/java/com/gcc/communityHall/controller/Admincontroller.java @@ -71,21 +71,21 @@ public class Admincontroller { @Autowired private UsersRepository usersRepository; - + @Autowired private BookingService bookingService; - + @Autowired private UserService userService; - @Autowired - private BookingDetailsRepository bookingDetailsRepository; - + @Autowired + private BookingDetailsRepository bookingDetailsRepository; + @Autowired private HallDetailsRepository hallDetailsRepo; - + @Autowired private DiscountRangeRepository discountRangeRepo; - + @Autowired private GccBlockingDateRepository blockingDateRepository; @@ -94,34 +94,34 @@ public class Admincontroller { @Autowired private AppConfig appConfig; - + @Autowired private JwtUtil jwtUtil; - + @Autowired private NotificationRepository notificationRepository; - + @Autowired private ApplicationLogsRepository applicationLogsRepository; - + @Autowired private TransactionResponseRepository transactionResponseRepository; - + @GetMapping("/dashboard") public String viewDashboard( @RequestParam(required = false, defaultValue = "all zones") String zone, Model model, HttpSession session) { - String token = (String) session.getAttribute("jwtToken"); - // System.out.println("tokensssssssss"+token); + 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); + //System.out.println("tokennnnnnnnnnnnnnns"+token); // Token is valid, proceed with dashboard logic String adminName = (String) session.getAttribute("usertype"); - long mobileno = (long) session.getAttribute("mobileno"); - model.addAttribute("mobileno", mobileno); + long mobileno = (long) session.getAttribute("mobileno"); + model.addAttribute("mobileno", mobileno); List> getMonthCount = bookingDetailsRepository.getAllAdminmonthcount(zone); List> count = bookingDetailsRepository.getAdmincount(zone); Map map = count.get(0); @@ -148,241 +148,240 @@ public class Admincontroller { @GetMapping("/Reports") public String viewReports(Model model,HttpSession session) { - String adminname = (String) session.getAttribute("usertype"); - if(adminname != null) { - long mobileno = (long) session.getAttribute("mobileno"); - model.addAttribute("adminname", adminname); - model.addAttribute("mobileno", mobileno); - return "admin/reports"; - }else { - session.invalidate(); // Invalidate the session to clear all session attributes - return "redirect:/communityhall/login"; - } + String adminname = (String) session.getAttribute("usertype"); + if(adminname != null) { + long mobileno = (long) session.getAttribute("mobileno"); + model.addAttribute("mobileno", mobileno); + return "admin/reports"; + }else { + session.invalidate(); // Invalidate the session to clear all session attributes + return "redirect:/communityhall/login"; } - + } + @GetMapping("/getReport") public String getReports(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/reports"; - }else { - session.invalidate(); // Invalidate the session to clear all session attributes - return "redirect:/communityhall/login"; - } + String adminname = (String) session.getAttribute("usertype"); + if(adminname != null) { + long mobileno = (long) session.getAttribute("mobileno"); + model.addAttribute("mobileno", mobileno); + return "admin/reports"; + }else { + session.invalidate(); // Invalidate the session to clear all session attributes + return "redirect:/communityhall/login"; } - - + } + + @GetMapping("/HallDetails") public String viewHallDetails(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/halldetailslist"; - }else { - session.invalidate(); // Invalidate the session to clear all session attributes - return "redirect:/communityhall/login"; - } - + String adminname = (String) session.getAttribute("usertype"); + if(adminname != null) { + long mobileno = (long) session.getAttribute("mobileno"); + model.addAttribute("mobileno", mobileno); + return "admin/halldetailslist"; + }else { + session.invalidate(); // Invalidate the session to clear all session attributes + return "redirect:/communityhall/login"; +} + } @GetMapping("/halldetailslist") public String viewhalldetailsList(Model model,HttpSession session) { - List list=hallDetailsRepo.findAll(); - String adminname = (String) session.getAttribute("usertype"); - if(adminname != null) { - long mobileno = (long) session.getAttribute("mobileno"); - model.addAttribute("mobileno", mobileno); - model.addAttribute("adminname", adminname); - model.addAttribute("halllist", list); - return "admin/halldetailslist"; - }else { - session.invalidate(); // Invalidate the session to clear all session attributes - return "redirect:/communityhall/login"; - } - + List list=hallDetailsRepo.findAll(); + String adminname = (String) session.getAttribute("usertype"); + if(adminname != null) { + long mobileno = (long) session.getAttribute("mobileno"); + model.addAttribute("mobileno", mobileno); + model.addAttribute("adminname", adminname); + model.addAttribute("halllist", list); + return "admin/halldetailslist"; + }else { + session.invalidate(); // Invalidate the session to clear all session attributes + return "redirect:/communityhall/login"; + } + } - + @GetMapping("/settlement-approved") public String viewSettlementMaster(Model model, HttpSession session) { String adminname = (String) session.getAttribute("usertype"); if(adminname != null) { - long mobileno = (long) session.getAttribute("mobileno"); - model.addAttribute("mobileno", mobileno); - List approvedSettlements = bookingDetailsRepository.findAllWithApprovedRefundStatus(); + long mobileno = (long) session.getAttribute("mobileno"); + model.addAttribute("mobileno", mobileno); + List approvedSettlements = bookingDetailsRepository.findAllWithApprovedRefundStatus(); List settlements = new ArrayList<>(); - settlements.addAll(approvedSettlements); - List approvedcancelledbookings=bookingDetailsRepository.findCancelledList(); - List approvedrejectedbookings=bookingDetailsRepository.findRejectedList(); - model.addAttribute("adminname", adminname); - model.addAttribute("settlementlist", settlements); - model.addAttribute("approvedcancelledbookings",approvedcancelledbookings); - model.addAttribute("approvedrejectedbookings",approvedrejectedbookings); - return "admin/settlement-approved"; + settlements.addAll(approvedSettlements); + List approvedcancelledbookings=bookingDetailsRepository.findCancelledList(); + List approvedrejectedbookings=bookingDetailsRepository.findRejectedList(); + model.addAttribute("adminname", adminname); + model.addAttribute("settlementlist", settlements); + model.addAttribute("approvedcancelledbookings",approvedcancelledbookings); + model.addAttribute("approvedrejectedbookings",approvedrejectedbookings); + return "admin/settlement-approved"; }else { - session.invalidate(); // Invalidate the session to clear all session attributes + session.invalidate(); // Invalidate the session to clear all session attributes return "redirect:/communityhall/login"; } } @GetMapping("/settlement-initiatedlist") public String viewSettlementInitiatedMaster(Model model,HttpSession session) { - String adminname = (String) session.getAttribute("usertype"); - if(adminname != null) { - long mobileno = (long) session.getAttribute("mobileno"); - model.addAttribute("mobileno", mobileno); - List settlement=bookingDetailsRepository.findByBookingDetailsRefundStatus(); - List Initiatedcancelledbookings=bookingDetailsRepository.findInitiatedCancelledList(); - List Initiatedrejectedbookings=bookingDetailsRepository.findInitiatedRejectedList(); - model.addAttribute("title","settlement initiate"); - model.addAttribute("adminname", adminname); - model.addAttribute("settlementlist",settlement); - model.addAttribute("Initiatedcancelledbookings",Initiatedcancelledbookings); - model.addAttribute("Initiatedrejectedbookings",Initiatedrejectedbookings); - return "admin/settlement-initiate"; - }else { - session.invalidate(); // Invalidate the session to clear all session attributes + String adminname = (String) session.getAttribute("usertype"); + if(adminname != null) { + long mobileno = (long) session.getAttribute("mobileno"); + model.addAttribute("mobileno", mobileno); + List settlement=bookingDetailsRepository.findByBookingDetailsRefundStatus(); + List Initiatedcancelledbookings=bookingDetailsRepository.findInitiatedCancelledList(); + List Initiatedrejectedbookings=bookingDetailsRepository.findInitiatedRejectedList(); + model.addAttribute("title","settlement initiate"); + model.addAttribute("adminname", adminname); + model.addAttribute("settlementlist",settlement); + model.addAttribute("Initiatedcancelledbookings",Initiatedcancelledbookings); + model.addAttribute("Initiatedrejectedbookings",Initiatedrejectedbookings); + return "admin/settlement-initiate"; + }else { + session.invalidate(); // Invalidate the session to clear all session attributes return "redirect:/communityhall/login"; - } + } } - + @GetMapping("/settlement-list") public String settlementPendingList(Model model,HttpSession session) { - String adminname = (String) session.getAttribute("usertype"); - if(adminname!=null) { - model.addAttribute("adminname", adminname); - long mobileno = (long) session.getAttribute("mobileno"); - model.addAttribute("mobileno", mobileno); - model.addAttribute("title","settlement Pending"); - String zone = (String) session.getAttribute("zone"); - model.addAttribute("zone", zone); - List settlement=bookingDetailsRepository.findAllSettlementPending(); - List cancelledbookings=bookingDetailsRepository.findAllSettlementCancelledList(); - List rejectedbookings=bookingDetailsRepository.findAllSettlementRejectedList(); - model.addAttribute("settlementlist",settlement); - model.addAttribute("cancelledbookings",cancelledbookings); - model.addAttribute("rejectedbookings",rejectedbookings); - return "admin/settlement-list"; - }else { - session.invalidate(); - return "redirect:/communityhall/login"; - } - } - + String adminname = (String) session.getAttribute("usertype"); + if(adminname!=null) { + model.addAttribute("adminname", adminname); + long mobileno = (long) session.getAttribute("mobileno"); + model.addAttribute("mobileno", mobileno); + model.addAttribute("title","settlement Pending"); + String zone = (String) session.getAttribute("zone"); + model.addAttribute("zone", zone); + List settlement=bookingDetailsRepository.findAllSettlementPending(); + List cancelledbookings=bookingDetailsRepository.findAllSettlementCancelledList(); + List rejectedbookings=bookingDetailsRepository.findAllSettlementRejectedList(); + model.addAttribute("settlementlist",settlement); + model.addAttribute("cancelledbookings",cancelledbookings); + model.addAttribute("rejectedbookings",rejectedbookings); + return "admin/settlement-list"; + }else { + session.invalidate(); + return "redirect:/communityhall/login"; + } +} + @GetMapping("/refundfailed-list") - public String RefundFailedList(Model model,HttpSession session) { - String adminname = (String) session.getAttribute("usertype"); - if(adminname!=null) { - model.addAttribute("adminname", adminname); - long mobileno = (long) session.getAttribute("mobileno"); - model.addAttribute("mobileno", mobileno); - model.addAttribute("title","settlementapproved"); - String zone = (String) session.getAttribute("zone"); - model.addAttribute("zone", zone); - List settlementrefundfailed=bookingDetailsRepository.findAllSettlementRefundFailed(); - List refundfailedcancelledbookings=bookingDetailsRepository.findAllRefundFaileCancelledList(); - List refundfailedrejectedbookings=bookingDetailsRepository.findAllRefundFaileRejectedList(); - model.addAttribute("settlementrefundfailed",settlementrefundfailed); - model.addAttribute("refundfailedcancelledbookings",refundfailedcancelledbookings); - model.addAttribute("refundfailedrejectedbookings",refundfailedrejectedbookings); - return "admin/refund-failedlist"; - } - else { - session.invalidate(); - return "redirect:/communityhall/login"; - } - } +public String RefundFailedList(Model model,HttpSession session) { + String adminname = (String) session.getAttribute("usertype"); + if(adminname!=null) { + model.addAttribute("adminname", adminname); + long mobileno = (long) session.getAttribute("mobileno"); + model.addAttribute("mobileno", mobileno); + model.addAttribute("title","settlementapproved"); + String zone = (String) session.getAttribute("zone"); + model.addAttribute("zone", zone); + List settlementrefundfailed=bookingDetailsRepository.findAllSettlementRefundFailed(); + List refundfailedcancelledbookings=bookingDetailsRepository.findAllRefundFaileCancelledList(); + List refundfailedrejectedbookings=bookingDetailsRepository.findAllRefundFaileRejectedList(); + model.addAttribute("settlementrefundfailed",settlementrefundfailed); + model.addAttribute("refundfailedcancelledbookings",refundfailedcancelledbookings); + model.addAttribute("refundfailedrejectedbookings",refundfailedrejectedbookings); + return "admin/refund-failedlist"; +} +else { + session.invalidate(); + return "redirect:/communityhall/login"; +} +} @GetMapping("/settlement-completedlist") public String viewSettlementcompletedMaster(Model model,HttpSession session) { - String adminname = (String) session.getAttribute("usertype"); - if(adminname != null) { - long mobileno = (long) session.getAttribute("mobileno"); - model.addAttribute("mobileno", mobileno); - List completedlist=bookingDetailsRepository.findSettlementCompletedList(); - List cancelledcompletedlist=bookingDetailsRepository.findCancelledCompletedList(); - List rejectedcompletedlist=bookingDetailsRepository.findRejectedSettlementCompletedList(); - model.addAttribute("title","settlement initiate"); - model.addAttribute("adminname", adminname); - model.addAttribute("completedlist",completedlist); - model.addAttribute("cancelledcompletedlist",cancelledcompletedlist); - model.addAttribute("rejectedcompletedlist",rejectedcompletedlist); - return "admin/settlement-completed"; - }else { - session.invalidate(); // Invalidate the session to clear all session attributes + String adminname = (String) session.getAttribute("usertype"); + if(adminname != null) { + long mobileno = (long) session.getAttribute("mobileno"); + model.addAttribute("mobileno", mobileno); + List completedlist=bookingDetailsRepository.findSettlementCompletedList(); + List cancelledcompletedlist=bookingDetailsRepository.findCancelledCompletedList(); + List rejectedcompletedlist=bookingDetailsRepository.findRejectedSettlementCompletedList(); + model.addAttribute("title","settlement initiate"); + model.addAttribute("adminname", adminname); + model.addAttribute("completedlist",completedlist); + model.addAttribute("cancelledcompletedlist",cancelledcompletedlist); + model.addAttribute("rejectedcompletedlist",rejectedcompletedlist); + return "admin/settlement-completed"; + }else { + session.invalidate(); // Invalidate the session to clear all session attributes return "redirect:/communityhall/login"; - } + } } @GetMapping("/ReasonMaster") public String viewreasonMaster(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/reasonmaster"; - }else { - session.invalidate(); // Invalidate the session to clear all session attributes - return "redirect:/communityhall/login"; - } - } + 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/reasonmaster"; + }else { + session.invalidate(); // Invalidate the session to clear all session attributes + return "redirect:/communityhall/login"; + } +} @GetMapping("/userdeactive") public String viewuserDetails(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/userdetails"; - }else { - session.invalidate(); // Invalidate the session to clear all session attributes - return "redirect:/communityhall/login"; - } + 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/userdetails"; + }else { + session.invalidate(); // Invalidate the session to clear all session attributes + return "redirect:/communityhall/login"; + } } @GetMapping("/Gccblocking") public String viewGccBlocking(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); - // 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 - } + long mobileno = (long) session.getAttribute("mobileno"); + model.addAttribute("mobileno", mobileno); + model.addAttribute("adminname", adminname); + // Fetch all blocked GCC dates + List gccBlocked = blockingDateRepository.findAllBlocked(); + + // Ensure distinct by hallId, blockingReason, startDate, and endDate + List uniqueGccBlockingDates = gccBlocked.stream() + .filter(distinctByKey(g -> Arrays.asList( + g.getHallId(), + g.getBlockingReason(), + g.getStartDate(), + g.getEndDate()))) + .collect(Collectors.toList()); + + // Map to store the count of blocked halls for each GccBlockingDate + Map hallCountMap = new HashMap<>(); + for (GccBlockingDate blockedDate : uniqueGccBlockingDates) { + // Parse and count unique hall IDs + String hallIds = blockedDate.getHallId(); + if (hallIds != null && !hallIds.isEmpty()) { + Set uniqueHallIds = new HashSet<>(Arrays.asList(hallIds.split(","))); + int hallCount = uniqueHallIds.size(); + hallCountMap.put(blockedDate.getBlockingId(), hallCount); + } else { + hallCountMap.put(blockedDate.getBlockingId(), 0); // No halls blocked } + } - // Add attributes to the model for the view - model.addAttribute("gccblocked", uniqueGccBlockingDates); - model.addAttribute("hallCountMap", hallCountMap); + // Add attributes to the model for the view + model.addAttribute("gccblocked", uniqueGccBlockingDates); + model.addAttribute("hallCountMap", hallCountMap); - return "admin/gccblocking"; - }else { - session.invalidate(); // Invalidate the session to clear all session attributes - return "redirect:/communityhall/login"; - } + return "admin/gccblocking"; + }else { + session.invalidate(); // Invalidate the session to clear all session attributes + return "redirect:/communityhall/login"; + } } @@ -419,174 +418,135 @@ public class Admincontroller { @RequestParam String hallInchargeName, @RequestParam long hallInchargeNo, @RequestParam("hallImages") MultipartFile[] hallImages,HttpSession session) { - String updatedId = (String) session.getAttribute("employeeId"); + 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); 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("Adding New Hall:-"+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); + Integer loginid = (Integer) session.getAttribute("id"); + ApplicationLogs logs=new ApplicationLogs(); + logs.setComments("Action by " + adminname); + logs.setLoginId(loginid); + logs.setLogType("Adding New Hall:-"+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); // Redirect to a success page or return a ModelAndView as per your application flow return "redirect:/communityhall/admin/halldetailslist"; } @GetMapping("/approval-history") public String viewApproval(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); - model.addAttribute("adminname", adminname); - model.addAttribute("title", "approvalcontrol"); - List Pending=usersRepository.getPendingList(); - String zone = (String) session.getAttribute("zone"); - model.addAttribute("zone", zone); - model.addAttribute("pendinglist",Pending); - return "admin/approval-history"; - }else { - session.invalidate(); // Invalidate the session to clear all session attributes + String adminname = (String) session.getAttribute("usertype"); + if(adminname != null) { + long mobileno = (long) session.getAttribute("mobileno"); + model.addAttribute("mobileno", mobileno); + model.addAttribute("adminname", adminname); + model.addAttribute("adminname", adminname); + model.addAttribute("title", "approvalcontrol"); + List Pending=usersRepository.getPendingList(); + String zone = (String) session.getAttribute("zone"); + model.addAttribute("zone", zone); + model.addAttribute("pendinglist",Pending); + return "admin/approval-history"; + }else { + session.invalidate(); // Invalidate the session to clear all session attributes return "redirect:/communityhall/login"; - } + } } @GetMapping("/user-approved") public String viewUserApproved(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); - model.addAttribute("title","reasondetails"); - List approved= usersRepository.getUserApproved(); - String zone = (String) session.getAttribute("zone"); - model.addAttribute("zone", zone); - model.addAttribute("approvedlist",approved); - return "admin/user-approved"; - }else { - session.invalidate(); // Invalidate the session to clear all session attributes - return "redirect:/communityhall/login"; - } + String adminname = (String) session.getAttribute("usertype"); + if(adminname != null) { + long mobileno = (long) session.getAttribute("mobileno"); + model.addAttribute("mobileno", mobileno); + model.addAttribute("adminname", adminname); + model.addAttribute("title","reasondetails"); + List approved= usersRepository.getUserApproved(); + String zone = (String) session.getAttribute("zone"); + model.addAttribute("zone", zone); + model.addAttribute("approvedlist",approved); + return "admin/user-approved"; + }else { + session.invalidate(); // Invalidate the session to clear all session attributes + return "redirect:/communityhall/login"; + } } @GetMapping("/user-reject") public String viewUserReject(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); - model.addAttribute("title","reasondetails"); - List reject= usersRepository.getUserReject(); - String zone = (String) session.getAttribute("zone"); - model.addAttribute("zone", zone); - model.addAttribute("rejectedlist",reject); - return "admin/user-reject"; - }else { - session.invalidate(); // Invalidate the session to clear all session attributes - return "redirect:/communityhall/login"; - } + String adminname = (String) session.getAttribute("usertype"); + if(adminname != null) { + long mobileno = (long) session.getAttribute("mobileno"); + model.addAttribute("mobileno", mobileno); + model.addAttribute("adminname", adminname); + model.addAttribute("title","reasondetails"); + List reject= usersRepository.getUserReject(); + String zone = (String) session.getAttribute("zone"); + model.addAttribute("zone", zone); + model.addAttribute("rejectedlist",reject); + return "admin/user-reject"; + }else { + session.invalidate(); // Invalidate the session to clear all session attributes + return "redirect:/communityhall/login"; + } } @GetMapping("/booking-list") public String viewBookingList(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); - List bookingList = bookingDetailsRepository.getAllApprovedList(); - model.addAttribute("bookingList", bookingList); - return "admin/booking-list"; // Assuming "officer/rejected-booking-list" is the name of your HTML template - }else { - session.invalidate(); // Invalidate the session to clear all session attributes + String adminname = (String) session.getAttribute("usertype"); + if(adminname != null) { + long mobileno = (long) session.getAttribute("mobileno"); + model.addAttribute("mobileno", mobileno); + model.addAttribute("adminname", adminname); + List bookingList = bookingDetailsRepository.getAllApprovedList(); + model.addAttribute("bookingList", bookingList); + return "admin/booking-list"; // Assuming "officer/rejected-booking-list" is the name of your HTML template + }else { + session.invalidate(); // Invalidate the session to clear all session attributes return "redirect:/communityhall/login"; - } + } } @GetMapping("/rejected-list") public String viewRejectedBookings(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); - List rejectedBookings = bookingDetailsRepository.getAllRejectingList(); - model.addAttribute("rejectedBookings", rejectedBookings); - - return "admin/rejected-list"; - }else { - session.invalidate(); // Invalidate the session to clear all session attributes + String adminname = (String) session.getAttribute("usertype"); + if(adminname != null) { + long mobileno = (long) session.getAttribute("mobileno"); + model.addAttribute("mobileno", mobileno); + model.addAttribute("adminname", adminname); + List rejectedBookings = bookingDetailsRepository.getAllRejectingList(); + model.addAttribute("rejectedBookings", rejectedBookings); + + return "admin/rejected-list"; + }else { + session.invalidate(); // Invalidate the session to clear all session attributes return "redirect:/communityhall/login"; - } + } } - -/* @GetMapping("/viewUploadNoc") - public String viewUploadNoc(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); - - // Fetch waiting bookings - List waitingBookings = bookingDetailsRepository.getAllwaitingNOC(); - System.out.println("Waiting Bookings: " + waitingBookings.size()); - model.addAttribute("waitingBookings", waitingBookings); - - return "admin/viewUploadNoc"; - } else { - session.invalidate(); // Invalidate the session to clear all session attributes - return "redirect:/communityhall/login"; - } - }*/ - + @GetMapping("/bookingwaitinglist") public String viewWaitingBookings(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); - List waitingBookings = bookingDetailsRepository.getAllwaitingList(); - model.addAttribute("waitingBookings", waitingBookings); - - return "admin/bookingwaiting"; - }else { - session.invalidate(); // Invalidate the session to clear all session attributes - return "redirect:/communityhall/login"; - } - } - - @GetMapping("/viewUploadNoc") - public String viewUploadNoc(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); - - // Fetch waiting bookings - List waitingBookings = bookingDetailsRepository.getAllwaitingNOC(); - System.out.println("Waiting Bookings: " + waitingBookings.size()); - model.addAttribute("waitingBookings", waitingBookings); - - return "admin/viewUploadNoc"; - } else { - session.invalidate(); // Invalidate the session to clear all session attributes + String adminname = (String) session.getAttribute("usertype"); + if(adminname != null) { + long mobileno = (long) session.getAttribute("mobileno"); + model.addAttribute("mobileno", mobileno); + model.addAttribute("adminname", adminname); + List waitingBookings = bookingDetailsRepository.getAllwaitingList(); + model.addAttribute("waitingBookings", waitingBookings); + + return "admin/bookingwaiting"; + }else { + session.invalidate(); // Invalidate the session to clear all session attributes return "redirect:/communityhall/login"; - } - } + } + } + @PostMapping("/getReport") public String generateReport(Model model, @RequestParam(name = "FromDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) String fromDate, @@ -603,113 +563,113 @@ public class Admincontroller { @RequestParam(name = "hall1",required = false, defaultValue = "1000") Integer hallid, @RequestParam(name = "basedon", required = false) String basedon, @RequestParam(name = "bookingId", required = false) Long bookingId,HttpSession session) { - 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 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); - } + 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 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); } - if (request.equals("8")) { - if (paymentStatus == null || paymentStatus.isEmpty()) { - extrapaymentList = bookingService.getAllExtraPaymentsDetails(fromDate, toDate, null,zone,division,hallid); - } else { - extrapaymentList = bookingService.getAllExtraPaymentsDetails(fromDate, toDate, paymentStatus,zone,division,hallid); - } + } + if (request.equals("8")) { + if (paymentStatus == null || paymentStatus.isEmpty()) { + extrapaymentList = bookingService.getAllExtraPaymentsDetails(fromDate, toDate, null,zone,division,hallid); + } else { + 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<>(); - // In your controller method - // Fetch booking count by zone - List totalcount = new ArrayList<>(); - int totalBookings = 0; - if ("7".equals(request)) { - if ("zone".equals(basedon)) { - totalcount = bookingDetailsRepository.countBookingsByZone(); - // Format zone data - totalcount = totalcount.stream() - .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] }) - .collect(Collectors.toList()); - } - - totalBookings = totalcount.stream() - .mapToInt(data -> ((Number) data[1]).intValue()) - .sum(); + } + 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<>(); + int totalBookings = 0; + if ("7".equals(request)) { + if ("zone".equals(basedon)) { + totalcount = bookingDetailsRepository.countBookingsByZone(); + // Format zone data + totalcount = totalcount.stream() + .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] }) + .collect(Collectors.toList()); } - model.addAttribute("basedon", basedon); - model.addAttribute("totalcount", totalcount); - model.addAttribute("totalBookings", totalBookings); - List hallbookingList = handleBookingHallDetailsReportRequest(request, fromDate, toDate, filterby,zone,division,hallid); - - model.addAttribute("filterby", filterby); - model.addAttribute("users", userList); - model.addAttribute("bookings", bookingList); - model.addAttribute("fromdate", fromDate); - model.addAttribute("todate", toDate); - model.addAttribute("userstatus", userstatus); - model.addAttribute("bookingSettlementList", bookingSettlementList); - model.addAttribute("usertype", usertype); - model.addAttribute("bookingStatus", bookingStatus); - model.addAttribute("refundStatus", refundStatus); - model.addAttribute("paymentStatus", paymentStatus); - model.addAttribute("request", request); - model.addAttribute("paymentLists", paymentList); - model.addAttribute("extrapaymentLists", extrapaymentList); - model.addAttribute("userbookingLists", userbookingList); - model.addAttribute("hallbookingLists", hallbookingList); - model.addAttribute("bookingId", bookingId); - model.addAttribute("zone1", zone); - model.addAttribute("division1", division); - model.addAttribute("hall1", hallid); - model.addAttribute("adminname", adminname); - - return "admin/reports"; - }else { - session.invalidate(); // Invalidate the session to clear all session attributes - return "redirect:/communityhall/login"; + totalBookings = totalcount.stream() + .mapToInt(data -> ((Number) data[1]).intValue()) + .sum(); } + model.addAttribute("basedon", basedon); + model.addAttribute("totalcount", totalcount); + model.addAttribute("totalBookings", totalBookings); + List hallbookingList = handleBookingHallDetailsReportRequest(request, fromDate, toDate, filterby,zone,division,hallid); + + + model.addAttribute("filterby", filterby); + model.addAttribute("users", userList); + model.addAttribute("bookings", bookingList); + model.addAttribute("fromdate", fromDate); + model.addAttribute("todate", toDate); + model.addAttribute("userstatus", userstatus); + model.addAttribute("bookingSettlementList", bookingSettlementList); + model.addAttribute("usertype", usertype); + model.addAttribute("bookingStatus", bookingStatus); + model.addAttribute("refundStatus", refundStatus); + model.addAttribute("paymentStatus", paymentStatus); + model.addAttribute("request", request); + model.addAttribute("paymentLists", paymentList); + model.addAttribute("extrapaymentLists", extrapaymentList); + model.addAttribute("userbookingLists", userbookingList); + model.addAttribute("hallbookingLists", hallbookingList); + model.addAttribute("bookingId", bookingId); + model.addAttribute("zone1", zone); + model.addAttribute("division1", division); + model.addAttribute("hall1", hallid); + model.addAttribute("adminname", adminname); + + return "admin/reports"; + }else { + session.invalidate(); // Invalidate the session to clear all session attributes + return "redirect:/communityhall/login"; } - + } + private List handleBookingHallDetailsReportRequest(String request, String fromDate, String toDate,String filterby,String zone,String division,Integer hallid) { - if (!request.equals("5")) { + if (!request.equals("5")) { return new ArrayList<>(); } - if(filterby.isEmpty()) - { - return bookingService.getBookingHallDetailsReportByBookingDate(fromDate, toDate,zone,division,hallid); - } - if ("1".equals(filterby)) + if(filterby.isEmpty()) + { + return bookingService.getBookingHallDetailsReportByBookingDate(fromDate, toDate,zone,division,hallid); + } + if ("1".equals(filterby)) { - - return bookingService.getBookingHallDetailsReportByBookingDate(fromDate, toDate,zone,division,hallid); - + + return bookingService.getBookingHallDetailsReportByBookingDate(fromDate, toDate,zone,division,hallid); + } - if ("2".equals(filterby)) + if ("2".equals(filterby)) { - - return bookingService.getBookingHallDetailsReportByEventDate(fromDate, toDate,zone,division,hallid); - + + return bookingService.getBookingHallDetailsReportByEventDate(fromDate, toDate,zone,division,hallid); + } - - return new ArrayList<>(); + + return new ArrayList<>(); } private List handleUserRequest(String request, String fromDate, String toDate, String userstatus, String usertype) { @@ -728,173 +688,173 @@ 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) { if (!request.equals("2")) { return new ArrayList<>(); } if(filterby.isEmpty() && bookingStatus.isEmpty() && bookingId == null) { - return bookingService.getBookingDetailsByBookingDate(fromDate, toDate,zone,division,hallid); + return bookingService.getBookingDetailsByBookingDate(fromDate, toDate,zone,division,hallid); } if(bookingId!=null && bookingStatus.isEmpty()) { - return bookingDetailsRepo.getAllBookingDetailsWithBookingId(fromDate, toDate, bookingId); + 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()) { - - if ("1".equals(filterby)) - { - if(bookingStatus.isEmpty()) - { - return bookingService.getBookingDetailsByBookingDate(fromDate, toDate,zone,division,hallid); - } - else - { - return bookingService.getBookingDetailsByBookingDateWithStatus(fromDate, toDate, bookingStatus,zone,division,hallid); - } - - } - if ("2".equals(filterby)) - { - if(bookingStatus.isEmpty()) - { - return bookingService.getBookingDetailsByEventDate(fromDate, toDate,zone,division,hallid); - } - else { - return bookingService.getBookingDetailsByEventDateWithStatus(fromDate, toDate, bookingStatus,zone,division,hallid); - } - - } + + if ("1".equals(filterby)) + { + if(bookingStatus.isEmpty()) + { + return bookingService.getBookingDetailsByBookingDate(fromDate, toDate,zone,division,hallid); + } + else + { + return bookingService.getBookingDetailsByBookingDateWithStatus(fromDate, toDate, bookingStatus,zone,division,hallid); + } + + } + if ("2".equals(filterby)) + { + if(bookingStatus.isEmpty()) + { + return bookingService.getBookingDetailsByEventDate(fromDate, toDate,zone,division,hallid); + } + else { + return bookingService.getBookingDetailsByEventDateWithStatus(fromDate, toDate, bookingStatus,zone,division,hallid); + } + + } } - // Handle default or error case - return new ArrayList<>(); + // Handle default or error case + return new ArrayList<>(); } - - + + private List handleBookingSettlementRequest(String request, String fromDate, String toDate, String refundStatus, String filterby) { if (!request.equals("6")) { return new ArrayList<>(); } if(filterby.isEmpty() && refundStatus.isEmpty()) { - return bookingService.getAllBookingsettlementDetailsByBookingDate(fromDate, toDate); + return bookingService.getAllBookingsettlementDetailsByBookingDate(fromDate, toDate); } if(filterby.isEmpty() && !refundStatus.isEmpty()) { - return bookingService.getAllBookingsettlementDetailsByBookingDateWithStatus(fromDate, toDate, refundStatus); + return bookingService.getAllBookingsettlementDetailsByBookingDateWithStatus(fromDate, toDate, refundStatus); } if(!filterby.isEmpty()) { - - if ("1".equals(filterby)) - { - if(refundStatus.isEmpty()) - { - return bookingService.getAllBookingsettlementDetailsByBookingDate(fromDate, toDate); - } - else - { - return bookingService.getAllBookingsettlementDetailsByBookingDateWithStatus(fromDate, toDate, refundStatus); - } - - } - if ("2".equals(filterby)) - { - if(refundStatus.isEmpty()) - { - return bookingService.getAllBookingsettlementDetailsByEventDate(fromDate, toDate); - } - else { - return bookingService.getAllBookingsettlementDetailsByEventDateWithStatus(fromDate, toDate, refundStatus); - } - - } + + if ("1".equals(filterby)) + { + if(refundStatus.isEmpty()) + { + return bookingService.getAllBookingsettlementDetailsByBookingDate(fromDate, toDate); + } + else + { + return bookingService.getAllBookingsettlementDetailsByBookingDateWithStatus(fromDate, toDate, refundStatus); + } + + } + if ("2".equals(filterby)) + { + if(refundStatus.isEmpty()) + { + return bookingService.getAllBookingsettlementDetailsByEventDate(fromDate, toDate); + } + else { + return bookingService.getAllBookingsettlementDetailsByEventDateWithStatus(fromDate, toDate, refundStatus); + } + + } } - - // Handle default or error case + + // Handle default or error case return new ArrayList<>(); } @GetMapping("/DiscountRange") public String viewDiscountRange(Model model,HttpSession session) { - String adminname = (String) session.getAttribute("usertype"); - if(adminname != null) { - long mobileno = (long) session.getAttribute("mobileno"); - model.addAttribute("mobileno", mobileno); - List discountRanges = discountRangeRepo.findAll(); - - model.addAttribute("discountRanges", discountRanges); - model.addAttribute("adminname", adminname); - return "admin/discountrange"; - }else { - session.invalidate(); // Invalidate the session to clear all session attributes + String adminname = (String) session.getAttribute("usertype"); + if(adminname != null) { + long mobileno = (long) session.getAttribute("mobileno"); + model.addAttribute("mobileno", mobileno); + List discountRanges = discountRangeRepo.findAll(); + + model.addAttribute("discountRanges", discountRanges); + model.addAttribute("adminname", adminname); + return "admin/discountrange"; + }else { + session.invalidate(); // Invalidate the session to clear all session attributes return "redirect:/communityhall/login"; - } + } } - + @GetMapping("/ongoingevents") public String viewRecentevents(Model model,HttpSession session) { - String adminname = (String) session.getAttribute("usertype"); - if(adminname != null) { - long mobileno = (long) session.getAttribute("mobileno"); - model.addAttribute("mobileno", mobileno); - List presenteventslist=bookingDetailsRepository.findPresentBookingList(); - List pasteventslist=bookingDetailsRepository.findPastEventsList(); - List futureeventslist=bookingDetailsRepository.findFutureEventsList(); - model.addAttribute("title","settlement initiate"); - model.addAttribute("adminname", adminname); - model.addAttribute("presenteventslist",presenteventslist); - model.addAttribute("pasteventslist",pasteventslist); - model.addAttribute("futureeventslist",futureeventslist); - return "admin/ongoingevents"; - }else { - session.invalidate(); // Invalidate the session to clear all session attributes + String adminname = (String) session.getAttribute("usertype"); + if(adminname != null) { + long mobileno = (long) session.getAttribute("mobileno"); + model.addAttribute("mobileno", mobileno); + List presenteventslist=bookingDetailsRepository.findPresentBookingList(); + List pasteventslist=bookingDetailsRepository.findPastEventsList(); + List futureeventslist=bookingDetailsRepository.findFutureEventsList(); + model.addAttribute("title","settlement initiate"); + model.addAttribute("adminname", adminname); + model.addAttribute("presenteventslist",presenteventslist); + model.addAttribute("pasteventslist",pasteventslist); + model.addAttribute("futureeventslist",futureeventslist); + return "admin/ongoingevents"; + }else { + session.invalidate(); // Invalidate the session to clear all session attributes return "redirect:/communityhall/login"; - } - } - + } + } + @GetMapping("/manualrefund") public String viewManualRefund(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/manualrefund"; - }else { - session.invalidate(); // Invalidate the session to clear all session attributes + 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/manualrefund"; + }else { + session.invalidate(); // Invalidate the session to clear all session attributes return "redirect:/communityhall/login"; - } + } } - + @GetMapping("/developer") public String viewDeveloper(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/developer"; - }else { - session.invalidate(); // Invalidate the session to clear all session attributes + 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/developer"; + }else { + session.invalidate(); // Invalidate the session to clear all session attributes return "redirect:/communityhall/login"; - } + } } - // @GetMapping("/getDeveloperdetails") +// @GetMapping("/getDeveloperdetails") // public String getDetails(Model model,HttpSession session) // { -// String adminname = (String) session.getAttribute("usertype"); +// String adminname = (String) session.getAttribute("usertype"); // if(adminname != null) { // long mobileno = (long) session.getAttribute("mobileno"); // model.addAttribute("mobileno", mobileno); @@ -904,43 +864,43 @@ public class Admincontroller { // 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) { - - - String adminname = (String) session.getAttribute("usertype"); - if(adminname != null) { - long mobileno = (long) session.getAttribute("mobileno"); - model.addAttribute("mobileno", mobileno); - List TransactionResponse = new ArrayList<>(); - if (request.equals("1")) { - if (bookingId == null && hallId == null) { - TransactionResponse = bookingService.getTransactionresponse(fromDate, toDate, null, null); - } else if (bookingId != null && hallId == null) { - TransactionResponse = bookingService.getTransactionresponse(fromDate, toDate, bookingId, null); - } else if (bookingId == null && hallId != null) { - TransactionResponse = bookingService.getTransactionresponse(fromDate, toDate, null, hallId); - } else { - TransactionResponse = bookingService.getTransactionresponse(fromDate, toDate, bookingId, hallId); - } +@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) { + + + String adminname = (String) session.getAttribute("usertype"); + if(adminname != null) { + long mobileno = (long) session.getAttribute("mobileno"); + model.addAttribute("mobileno", mobileno); + List TransactionResponse = new ArrayList<>(); + if (request.equals("1")) { + if (bookingId == null && hallId == null) { + TransactionResponse = bookingService.getTransactionresponse(fromDate, toDate, null, null); + } else if (bookingId != null && hallId == null) { + TransactionResponse = bookingService.getTransactionresponse(fromDate, toDate, bookingId, null); + } else if (bookingId == null && hallId != null) { + TransactionResponse = bookingService.getTransactionresponse(fromDate, toDate, null, hallId); + } else { + TransactionResponse = bookingService.getTransactionresponse(fromDate, toDate, bookingId, hallId); } - List RefundResponse = new ArrayList<>(); - if (request.equals("2")) { - if (bookingId == null) { - RefundResponse = bookingService.getRefundResponse(fromDate,toDate,null); - } else { - RefundResponse = bookingService.getRefundResponse(fromDate, toDate,bookingId); - } + } + List RefundResponse = new ArrayList<>(); + if (request.equals("2")) { + if (bookingId == null) { + RefundResponse = bookingService.getRefundResponse(fromDate,toDate,null); + } else { + RefundResponse = bookingService.getRefundResponse(fromDate, toDate,bookingId); } - List BookingCalendar = new ArrayList<>(); - if (request.equals("3")) { - System.out.println("outside"); + } + 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 @@ -950,67 +910,65 @@ public class Admincontroller { // // Fetch filtered details based on hallName // BookingCalendar = bookingService.getBookingCalendarDetails(fromDate, toDate, hallName); // } - BookingCalendar = bookingService.getBookingCalendarDetails(fromDate, toDate,bookingId,hallName); - } - - model.addAttribute("fromdate", fromDate); - model.addAttribute("todate", toDate); - model.addAttribute("request", request); - model.addAttribute("TransactionResponse", TransactionResponse); - model.addAttribute("RefundResponse", RefundResponse); - model.addAttribute("BookingCalendar", BookingCalendar); - model.addAttribute("bookingId", bookingId); - model.addAttribute("hallId", hallId); - model.addAttribute("hallName", hallName); - model.addAttribute("adminname", adminname); - - return "admin/developer"; - }else { - session.invalidate(); // Invalidate the session to clear all session attributes - return "redirect:/communityhall/login"; + BookingCalendar = bookingService.getBookingCalendarDetails(fromDate, toDate,bookingId,hallName); } - } + model.addAttribute("fromdate", fromDate); + model.addAttribute("todate", toDate); + model.addAttribute("request", request); + model.addAttribute("TransactionResponse", TransactionResponse); + model.addAttribute("RefundResponse", RefundResponse); + model.addAttribute("BookingCalendar", BookingCalendar); + model.addAttribute("bookingId", bookingId); + model.addAttribute("hallId", hallId); + model.addAttribute("hallName", hallName); + model.addAttribute("adminname", adminname); + + return "admin/developer"; + }else { + session.invalidate(); // Invalidate the session to clear all session attributes + return "redirect:/communityhall/login"; + } +} + @GetMapping("/notification") public String viewNotificationPage(Model model,HttpSession session) { - String adminname = (String) session.getAttribute("usertype"); - if(adminname != null) { - long mobileno = (long) session.getAttribute("mobileno"); - List newnotifications=notificationRepository.findActivenotifications(); - model.addAttribute("newnotifications", newnotifications); - model.addAttribute("mobileno", mobileno); - model.addAttribute("adminname", adminname); - return "admin/notification"; - }else { - session.invalidate(); // Invalidate the session to clear all session attributes + String adminname = (String) session.getAttribute("usertype"); + if(adminname != null) { + long mobileno = (long) session.getAttribute("mobileno"); + List newnotifications=notificationRepository.findActivenotifications(); + model.addAttribute("newnotifications", newnotifications); + model.addAttribute("mobileno", mobileno); + model.addAttribute("adminname", adminname); + return "admin/notification"; + }else { + session.invalidate(); // Invalidate the session to clear all session attributes return "redirect:/communityhall/login"; - } + } } - + @GetMapping("/raisesettlement") public String viewcaretakerpage(Model model,HttpSession session,@RequestParam("bookingId") int bookingId) { - String adminname = (String) session.getAttribute("usertype"); - if(adminname!=null) { - long mobileno = (long) session.getAttribute("mobileno"); - model.addAttribute("mobileno", mobileno); - model.addAttribute("adminname", adminname); - BookingDetails booking = bookingService.getBookingsById(bookingId); - model.addAttribute("booking",booking); - return "admin/caretakerpage"; - }else { - session.invalidate(); - return "redirect:/communityhall/login"; - } + String adminname = (String) session.getAttribute("usertype"); + if(adminname!=null) { + long mobileno = (long) session.getAttribute("mobileno"); + model.addAttribute("mobileno", mobileno); + model.addAttribute("adminname", adminname); + BookingDetails booking = bookingService.getBookingsById(bookingId); + model.addAttribute("booking",booking); + return "admin/caretakerpage"; + }else { + session.invalidate(); + return "redirect:/communityhall/login"; + } } @GetMapping("/settlementlist") public String viewSettlementList(Model model, HttpSession session) { - String adminname = (String) session.getAttribute("usertype"); - if (adminname != null) { + String userType = (String) session.getAttribute("usertype"); + if (userType != null) { List settlemetList = bookingRepository.getAllSettlementList(); model.addAttribute("settlemetList", settlemetList); - model.addAttribute("adminname", adminname); - return "admin/settlementlist"; } else { session.invalidate(); @@ -1038,11 +996,10 @@ public class Admincontroller { @GetMapping("/settlement-reject") public String settlementRejectedList(Model model, HttpSession session) { - String adminname = (String) session.getAttribute("usertype"); - if (adminname != null) { + String userType = (String) session.getAttribute("usertype"); + if (userType != null) { List settlement = bookingDetailsRepository.findAllSettlementRejected(); model.addAttribute("title", "Settlement Rejected"); - model.addAttribute("adminname", adminname); model.addAttribute("rejectSettlementlist", settlement); return "admin/settlement-reject"; } else { @@ -1054,9 +1011,29 @@ public class Admincontroller { @GetMapping("/logout") public String viewLogout(Model model,HttpSession session) { - session.invalidate(); + session.invalidate(); return "redirect:/communityhall/login"; } + @GetMapping("/viewUploadNoc") + public String viewUploadNoc(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); + + // Fetch waiting bookings + List waitingBookings = bookingDetailsRepository.getAllwaitingNOC(); + System.out.println("Waiting Bookings: " + waitingBookings.size()); + model.addAttribute("waitingBookings", waitingBookings); + + return "admin/viewUploadNoc"; + } 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/HeadquartersController.java b/src/main/java/com/gcc/communityHall/controller/HeadquartersController.java index 10fed7ca..8a1615a1 100644 --- a/src/main/java/com/gcc/communityHall/controller/HeadquartersController.java +++ b/src/main/java/com/gcc/communityHall/controller/HeadquartersController.java @@ -1,10 +1,12 @@ package com.gcc.communityHall.controller; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; +import java.util.*; +import java.util.function.Function; +import java.util.function.Predicate; import java.util.stream.Collectors; +import com.gcc.communityHall.entity.GccBlockingDate; import com.gcc.communityHall.others.AppConfig; +import com.gcc.communityHall.repository.GccBlockingDateRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.stereotype.Controller; @@ -46,6 +48,9 @@ public class HeadquartersController { @Autowired private BookingDetailsRepository bookingDetailsRepository; + @Autowired + private GccBlockingDateRepository blockingDateRepository; + @Autowired private AppConfig appConfig; @@ -183,113 +188,113 @@ public class HeadquartersController { @RequestParam(name = "hall1",required = false, defaultValue = "1000") Integer hallid, @RequestParam(name = "basedon", required = false) String basedon, @RequestParam(name = "bookingId", required = false) Long bookingId,HttpSession session) { - String headquartersname = (String) session.getAttribute("usertype"); - if(headquartersname != 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 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); - } + String headquartersname = (String) session.getAttribute("usertype"); + if(headquartersname != 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 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); } - if (request.equals("8")) { - if (paymentStatus == null || paymentStatus.isEmpty()) { - extrapaymentList = bookingService.getAllExtraPaymentsDetails(fromDate, toDate, null,zone,division,hallid); - } else { - extrapaymentList = bookingService.getAllExtraPaymentsDetails(fromDate, toDate, paymentStatus,zone,division,hallid); - } + } + if (request.equals("8")) { + if (paymentStatus == null || paymentStatus.isEmpty()) { + extrapaymentList = bookingService.getAllExtraPaymentsDetails(fromDate, toDate, null,zone,division,hallid); + } else { + 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<>(); - // In your controller method - // Fetch booking count by zone - List totalcount = new ArrayList<>(); - int totalBookings = 0; - if ("7".equals(request)) { - if ("zone".equals(basedon)) { - totalcount = bookingDetailsRepository.countBookingsByZone(); - // Format zone data - totalcount = totalcount.stream() - .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] }) - .collect(Collectors.toList()); - } - - totalBookings = totalcount.stream() - .mapToInt(data -> ((Number) data[1]).intValue()) - .sum(); + } + 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<>(); + int totalBookings = 0; + if ("7".equals(request)) { + if ("zone".equals(basedon)) { + totalcount = bookingDetailsRepository.countBookingsByZone(); + // Format zone data + totalcount = totalcount.stream() + .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] }) + .collect(Collectors.toList()); } - model.addAttribute("basedon", basedon); - model.addAttribute("totalcount", totalcount); - model.addAttribute("totalBookings", totalBookings); - List hallbookingList = handleBookingHallDetailsReportRequest(request, fromDate, toDate, filterby,zone,division,hallid); - - - model.addAttribute("filterby", filterby); - model.addAttribute("users", userList); - model.addAttribute("bookings", bookingList); - model.addAttribute("fromdate", fromDate); - model.addAttribute("todate", toDate); - model.addAttribute("userstatus", userstatus); - model.addAttribute("bookingSettlementList", bookingSettlementList); - model.addAttribute("usertype", usertype); - model.addAttribute("bookingStatus", bookingStatus); - model.addAttribute("refundStatus", refundStatus); - model.addAttribute("paymentStatus", paymentStatus); - model.addAttribute("request", request); - model.addAttribute("paymentLists", paymentList); - model.addAttribute("extrapaymentLists", extrapaymentList); - model.addAttribute("userbookingLists", userbookingList); - model.addAttribute("hallbookingLists", hallbookingList); - model.addAttribute("bookingId", bookingId); - model.addAttribute("zone1", zone); - model.addAttribute("division1", division); - model.addAttribute("hall1", hallid); - model.addAttribute("headquartersname", headquartersname); - return "headquarters/reports"; - }else { - session.invalidate(); // Invalidate the session to clear all session attributes - return "redirect:/communityhall/login"; - } + totalBookings = totalcount.stream() + .mapToInt(data -> ((Number) data[1]).intValue()) + .sum(); + } + model.addAttribute("basedon", basedon); + model.addAttribute("totalcount", totalcount); + model.addAttribute("totalBookings", totalBookings); + List hallbookingList = handleBookingHallDetailsReportRequest(request, fromDate, toDate, filterby,zone,division,hallid); + + + model.addAttribute("filterby", filterby); + model.addAttribute("users", userList); + model.addAttribute("bookings", bookingList); + model.addAttribute("fromdate", fromDate); + model.addAttribute("todate", toDate); + model.addAttribute("userstatus", userstatus); + model.addAttribute("bookingSettlementList", bookingSettlementList); + model.addAttribute("usertype", usertype); + model.addAttribute("bookingStatus", bookingStatus); + model.addAttribute("refundStatus", refundStatus); + model.addAttribute("paymentStatus", paymentStatus); + model.addAttribute("request", request); + model.addAttribute("paymentLists", paymentList); + model.addAttribute("extrapaymentLists", extrapaymentList); + model.addAttribute("userbookingLists", userbookingList); + model.addAttribute("hallbookingLists", hallbookingList); + model.addAttribute("bookingId", bookingId); + model.addAttribute("zone1", zone); + model.addAttribute("division1", division); + model.addAttribute("hall1", hallid); + model.addAttribute("headquartersname", headquartersname); + + return "headquarters/reports"; + }else { + session.invalidate(); // Invalidate the session to clear all session attributes + return "redirect:/communityhall/login"; } - + } + private List handleBookingHallDetailsReportRequest(String request, String fromDate, String toDate,String filterby,String zone,String division,Integer hallid) { - if (!request.equals("5")) { + if (!request.equals("5")) { return new ArrayList<>(); } - if(filterby.isEmpty()) + if(filterby.isEmpty()) + { + return bookingService.getBookingHallDetailsReportByBookingDate(fromDate, toDate,zone,division,hallid); + } + if ("1".equals(filterby)) { - return bookingService.getBookingHallDetailsReportByBookingDate(fromDate, toDate,zone,division,hallid); + + return bookingService.getBookingHallDetailsReportByBookingDate(fromDate, toDate,zone,division,hallid); + } - if ("1".equals(filterby)) + if ("2".equals(filterby)) { - - return bookingService.getBookingHallDetailsReportByBookingDate(fromDate, toDate,zone,division,hallid); - + + return bookingService.getBookingHallDetailsReportByEventDate(fromDate, toDate,zone,division,hallid); + } - if ("2".equals(filterby)) - { - - return bookingService.getBookingHallDetailsReportByEventDate(fromDate, toDate,zone,division,hallid); - - } - - return new ArrayList<>(); + + return new ArrayList<>(); } private List handleUserRequest(String request, String fromDate, String toDate, String userstatus, String usertype) { @@ -308,101 +313,101 @@ public class HeadquartersController { 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) { if (!request.equals("2")) { return new ArrayList<>(); } if(filterby.isEmpty() && bookingStatus.isEmpty() && bookingId == null) { - return bookingService.getBookingDetailsByBookingDate(fromDate, toDate,zone,division,hallid); + return bookingService.getBookingDetailsByBookingDate(fromDate, toDate,zone,division,hallid); } if(bookingId!=null && bookingStatus.isEmpty()) { - return bookingDetailsRepo.getAllBookingDetailsWithBookingId(fromDate, toDate, bookingId); + 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()) { - - if ("1".equals(filterby)) - { - if(bookingStatus.isEmpty()) - { - return bookingService.getBookingDetailsByBookingDate(fromDate, toDate,zone,division,hallid); - } - else - { - return bookingService.getBookingDetailsByBookingDateWithStatus(fromDate, toDate, bookingStatus,zone,division,hallid); - } - - } - if ("2".equals(filterby)) - { - if(bookingStatus.isEmpty()) - { - return bookingService.getBookingDetailsByEventDate(fromDate, toDate,zone,division,hallid); - } - else { - return bookingService.getBookingDetailsByEventDateWithStatus(fromDate, toDate, bookingStatus,zone,division,hallid); - } - - } - } - // Handle default or error case - return new ArrayList<>(); + + if ("1".equals(filterby)) + { + if(bookingStatus.isEmpty()) + { + return bookingService.getBookingDetailsByBookingDate(fromDate, toDate,zone,division,hallid); + } + else + { + return bookingService.getBookingDetailsByBookingDateWithStatus(fromDate, toDate, bookingStatus,zone,division,hallid); + } + + } + if ("2".equals(filterby)) + { + if(bookingStatus.isEmpty()) + { + return bookingService.getBookingDetailsByEventDate(fromDate, toDate,zone,division,hallid); + } + else { + return bookingService.getBookingDetailsByEventDateWithStatus(fromDate, toDate, bookingStatus,zone,division,hallid); + } + + } + } + // Handle default or error case + return new ArrayList<>(); } - - + + private List handleBookingSettlementRequest(String request, String fromDate, String toDate, String refundStatus, String filterby) { if (!request.equals("6")) { return new ArrayList<>(); } if(filterby.isEmpty() && refundStatus.isEmpty()) { - return bookingService.getAllBookingsettlementDetailsByBookingDate(fromDate, toDate); + return bookingService.getAllBookingsettlementDetailsByBookingDate(fromDate, toDate); } if(filterby.isEmpty() && !refundStatus.isEmpty()) { - return bookingService.getAllBookingsettlementDetailsByBookingDateWithStatus(fromDate, toDate, refundStatus); + return bookingService.getAllBookingsettlementDetailsByBookingDateWithStatus(fromDate, toDate, refundStatus); } if(!filterby.isEmpty()) { - - if ("1".equals(filterby)) - { - if(refundStatus.isEmpty()) - { - return bookingService.getAllBookingsettlementDetailsByBookingDate(fromDate, toDate); - } - else - { - return bookingService.getAllBookingsettlementDetailsByBookingDateWithStatus(fromDate, toDate, refundStatus); - } - - } - if ("2".equals(filterby)) - { - if(refundStatus.isEmpty()) - { - return bookingService.getAllBookingsettlementDetailsByEventDate(fromDate, toDate); - } - else { - return bookingService.getAllBookingsettlementDetailsByEventDateWithStatus(fromDate, toDate, refundStatus); - } - - } - } - - // Handle default or error case + + if ("1".equals(filterby)) + { + if(refundStatus.isEmpty()) + { + return bookingService.getAllBookingsettlementDetailsByBookingDate(fromDate, toDate); + } + else + { + return bookingService.getAllBookingsettlementDetailsByBookingDateWithStatus(fromDate, toDate, refundStatus); + } + + } + if ("2".equals(filterby)) + { + if(refundStatus.isEmpty()) + { + return bookingService.getAllBookingsettlementDetailsByEventDate(fromDate, toDate); + } + else { + return bookingService.getAllBookingsettlementDetailsByEventDateWithStatus(fromDate, toDate, refundStatus); + } + + } + } + + // Handle default or error case return new ArrayList<>(); } @GetMapping("/ongoingevents") @@ -425,165 +430,165 @@ public class HeadquartersController { return "redirect:/communityhall/login"; } } - + @GetMapping("/booking-list") public String viewBookingList(Model model,HttpSession session) { - String headquartersname = (String) session.getAttribute("usertype"); - if(headquartersname != null) { - long mobileno = (long) session.getAttribute("mobileno"); - model.addAttribute("mobileno", mobileno); - model.addAttribute("headquartersname", headquartersname); - List bookingList = bookingDetailsRepository.getAllApprovedList(); - model.addAttribute("bookingList", bookingList); - return "headquarters/booking-list"; // Assuming "officer/rejected-booking-list" is the name of your HTML template - }else { - session.invalidate(); // Invalidate the session to clear all session attributes + String headquartersname = (String) session.getAttribute("usertype"); + if(headquartersname != null) { + long mobileno = (long) session.getAttribute("mobileno"); + model.addAttribute("mobileno", mobileno); + model.addAttribute("headquartersname", headquartersname); + List bookingList = bookingDetailsRepository.getAllApprovedList(); + model.addAttribute("bookingList", bookingList); + return "headquarters/booking-list"; // Assuming "officer/rejected-booking-list" is the name of your HTML template + }else { + session.invalidate(); // Invalidate the session to clear all session attributes return "redirect:/communityhall/login"; - } + } } @GetMapping("/rejected-list") public String viewRejectedBookings(Model model,HttpSession session) { - String headquartersname = (String) session.getAttribute("usertype"); - if(headquartersname != null) { - long mobileno = (long) session.getAttribute("mobileno"); - model.addAttribute("mobileno", mobileno); - model.addAttribute("headquartersname", headquartersname); - List rejectedBookings = bookingDetailsRepository.getAllRejectingList(); - model.addAttribute("rejectedBookings", rejectedBookings); - - return "headquarters/rejected-list"; - }else { - session.invalidate(); // Invalidate the session to clear all session attributes + String headquartersname = (String) session.getAttribute("usertype"); + if(headquartersname != null) { + long mobileno = (long) session.getAttribute("mobileno"); + model.addAttribute("mobileno", mobileno); + model.addAttribute("headquartersname", headquartersname); + List rejectedBookings = bookingDetailsRepository.getAllRejectingList(); + model.addAttribute("rejectedBookings", rejectedBookings); + + return "headquarters/rejected-list"; + }else { + session.invalidate(); // Invalidate the session to clear all session attributes return "redirect:/communityhall/login"; - } + } } - + @GetMapping("/bookingwaitinglist") public String viewWaitingBookings(Model model,HttpSession session) { - String headquartersname = (String) session.getAttribute("usertype"); - if(headquartersname != null) { - long mobileno = (long) session.getAttribute("mobileno"); - model.addAttribute("mobileno", mobileno); - model.addAttribute("headquartersname", headquartersname); - List waitingBookings = bookingDetailsRepository.getAllwaitingList(); - model.addAttribute("waitingBookings", waitingBookings); - - return "headquarters/bookingwaiting"; - }else { - session.invalidate(); // Invalidate the session to clear all session attributes + String headquartersname = (String) session.getAttribute("usertype"); + if(headquartersname != null) { + long mobileno = (long) session.getAttribute("mobileno"); + model.addAttribute("mobileno", mobileno); + model.addAttribute("headquartersname", headquartersname); + List waitingBookings = bookingDetailsRepository.getAllwaitingList(); + model.addAttribute("waitingBookings", waitingBookings); + + return "headquarters/bookingwaiting"; + }else { + session.invalidate(); // Invalidate the session to clear all session attributes return "redirect:/communityhall/login"; - } + } } - + @GetMapping("/settlement-approved") public String viewSettlementMaster(Model model, HttpSession session) { String headquartersname = (String) session.getAttribute("usertype"); if(headquartersname != null) { - long mobileno = (long) session.getAttribute("mobileno"); - model.addAttribute("mobileno", mobileno); - List approvedSettlements = bookingDetailsRepository.findAllWithApprovedRefundStatus(); + long mobileno = (long) session.getAttribute("mobileno"); + model.addAttribute("mobileno", mobileno); + List approvedSettlements = bookingDetailsRepository.findAllWithApprovedRefundStatus(); List settlements = new ArrayList<>(); - settlements.addAll(approvedSettlements); - List approvedcancelledbookings=bookingDetailsRepository.findCancelledList(); - List approvedrejectedbookings=bookingDetailsRepository.findRejectedList(); - model.addAttribute("headquartersname", headquartersname); - model.addAttribute("settlementlist", settlements); - model.addAttribute("approvedcancelledbookings",approvedcancelledbookings); - model.addAttribute("approvedrejectedbookings",approvedrejectedbookings); - return "headquarters/settlement-approved"; + settlements.addAll(approvedSettlements); + List approvedcancelledbookings=bookingDetailsRepository.findCancelledList(); + List approvedrejectedbookings=bookingDetailsRepository.findRejectedList(); + model.addAttribute("headquartersname", headquartersname); + model.addAttribute("settlementlist", settlements); + model.addAttribute("approvedcancelledbookings",approvedcancelledbookings); + model.addAttribute("approvedrejectedbookings",approvedrejectedbookings); + return "headquarters/settlement-approved"; }else { - session.invalidate(); // Invalidate the session to clear all session attributes + session.invalidate(); // Invalidate the session to clear all session attributes return "redirect:/communityhall/login"; } } @GetMapping("/settlement-initiatedlist") public String viewSettlementInitiatedMaster(Model model,HttpSession session) { - String headquartersname = (String) session.getAttribute("usertype"); - if(headquartersname != null) { - long mobileno = (long) session.getAttribute("mobileno"); - model.addAttribute("mobileno", mobileno); - List settlement=bookingDetailsRepository.findByBookingDetailsRefundStatus(); - List Initiatedcancelledbookings=bookingDetailsRepository.findInitiatedCancelledList(); - List Initiatedrejectedbookings=bookingDetailsRepository.findInitiatedRejectedList(); - model.addAttribute("title","settlement initiate"); - model.addAttribute("headquartersname", headquartersname); - model.addAttribute("settlementlist",settlement); - model.addAttribute("Initiatedcancelledbookings",Initiatedcancelledbookings); - model.addAttribute("Initiatedrejectedbookings",Initiatedrejectedbookings); - return "headquarters/settlement-initiate"; - }else { - session.invalidate(); // Invalidate the session to clear all session attributes + String headquartersname = (String) session.getAttribute("usertype"); + if(headquartersname != null) { + long mobileno = (long) session.getAttribute("mobileno"); + model.addAttribute("mobileno", mobileno); + List settlement=bookingDetailsRepository.findByBookingDetailsRefundStatus(); + List Initiatedcancelledbookings=bookingDetailsRepository.findInitiatedCancelledList(); + List Initiatedrejectedbookings=bookingDetailsRepository.findInitiatedRejectedList(); + model.addAttribute("title","settlement initiate"); + model.addAttribute("headquartersname", headquartersname); + model.addAttribute("settlementlist",settlement); + model.addAttribute("Initiatedcancelledbookings",Initiatedcancelledbookings); + model.addAttribute("Initiatedrejectedbookings",Initiatedrejectedbookings); + return "headquarters/settlement-initiate"; + }else { + session.invalidate(); // Invalidate the session to clear all session attributes return "redirect:/communityhall/login"; - } + } } - + @GetMapping("/settlement-list") public String settlementPendingList(Model model,HttpSession session) { - String headquartersname = (String) session.getAttribute("usertype"); - if(headquartersname!=null) { - model.addAttribute("headquartersname", headquartersname); - long mobileno = (long) session.getAttribute("mobileno"); - model.addAttribute("mobileno", mobileno); - model.addAttribute("title","settlement Pending"); - String zone = (String) session.getAttribute("zone"); - model.addAttribute("zone", zone); - List settlement=bookingDetailsRepository.findAllSettlementPending(); - List cancelledbookings=bookingDetailsRepository.findAllSettlementCancelledList(); - List rejectedbookings=bookingDetailsRepository.findAllSettlementRejectedList(); - model.addAttribute("settlementlist",settlement); - model.addAttribute("cancelledbookings",cancelledbookings); - model.addAttribute("rejectedbookings",rejectedbookings); - return "headquarters/settlement-list"; - }else { - session.invalidate(); - return "redirect:/communityhall/login"; - } - } - + String headquartersname = (String) session.getAttribute("usertype"); + if(headquartersname!=null) { + model.addAttribute("headquartersname", headquartersname); + long mobileno = (long) session.getAttribute("mobileno"); + model.addAttribute("mobileno", mobileno); + model.addAttribute("title","settlement Pending"); + String zone = (String) session.getAttribute("zone"); + model.addAttribute("zone", zone); + List settlement=bookingDetailsRepository.findAllSettlementPending(); + List cancelledbookings=bookingDetailsRepository.findAllSettlementCancelledList(); + List rejectedbookings=bookingDetailsRepository.findAllSettlementRejectedList(); + model.addAttribute("settlementlist",settlement); + model.addAttribute("cancelledbookings",cancelledbookings); + model.addAttribute("rejectedbookings",rejectedbookings); + return "headquarters/settlement-list"; + }else { + session.invalidate(); + return "redirect:/communityhall/login"; + } +} + @GetMapping("/refundfailed-list") - public String RefundFailedList(Model model,HttpSession session) { - String headquartersname = (String) session.getAttribute("usertype"); - if(headquartersname!=null) { - model.addAttribute("headquartersname", headquartersname); - long mobileno = (long) session.getAttribute("mobileno"); - model.addAttribute("mobileno", mobileno); - model.addAttribute("title","settlementapproved"); - String zone = (String) session.getAttribute("zone"); - model.addAttribute("zone", zone); - List settlementrefundfailed=bookingDetailsRepository.findAllSettlementRefundFailed(); - List refundfailedcancelledbookings=bookingDetailsRepository.findAllRefundFaileCancelledList(); - List refundfailedrejectedbookings=bookingDetailsRepository.findAllRefundFaileRejectedList(); - model.addAttribute("settlementrefundfailed",settlementrefundfailed); - model.addAttribute("refundfailedcancelledbookings",refundfailedcancelledbookings); - model.addAttribute("refundfailedrejectedbookings",refundfailedrejectedbookings); - return "headquarters/refund-failedlist"; - } - else { - session.invalidate(); - return "redirect:/communityhall/login"; - } - } +public String RefundFailedList(Model model,HttpSession session) { + String headquartersname = (String) session.getAttribute("usertype"); + if(headquartersname!=null) { + model.addAttribute("headquartersname", headquartersname); + long mobileno = (long) session.getAttribute("mobileno"); + model.addAttribute("mobileno", mobileno); + model.addAttribute("title","settlementapproved"); + String zone = (String) session.getAttribute("zone"); + model.addAttribute("zone", zone); + List settlementrefundfailed=bookingDetailsRepository.findAllSettlementRefundFailed(); + List refundfailedcancelledbookings=bookingDetailsRepository.findAllRefundFaileCancelledList(); + List refundfailedrejectedbookings=bookingDetailsRepository.findAllRefundFaileRejectedList(); + model.addAttribute("settlementrefundfailed",settlementrefundfailed); + model.addAttribute("refundfailedcancelledbookings",refundfailedcancelledbookings); + model.addAttribute("refundfailedrejectedbookings",refundfailedrejectedbookings); + return "headquarters/refund-failedlist"; +} +else { + session.invalidate(); + return "redirect:/communityhall/login"; +} +} @GetMapping("/settlement-completedlist") public String viewSettlementcompletedMaster(Model model,HttpSession session) { - String headquartersname = (String) session.getAttribute("usertype"); - if(headquartersname != null) { - long mobileno = (long) session.getAttribute("mobileno"); - model.addAttribute("mobileno", mobileno); - List completedlist=bookingDetailsRepository.findSettlementCompletedList(); - List cancelledcompletedlist=bookingDetailsRepository.findCancelledCompletedList(); - List rejectedcompletedlist=bookingDetailsRepository.findRejectedSettlementCompletedList(); - model.addAttribute("title","settlement initiate"); - model.addAttribute("headquartersname", headquartersname); - model.addAttribute("completedlist",completedlist); - model.addAttribute("cancelledcompletedlist",cancelledcompletedlist); - model.addAttribute("rejectedcompletedlist",rejectedcompletedlist); - return "headquarters/settlement-completed"; - }else { - session.invalidate(); // Invalidate the session to clear all session attributes + String headquartersname = (String) session.getAttribute("usertype"); + if(headquartersname != null) { + long mobileno = (long) session.getAttribute("mobileno"); + model.addAttribute("mobileno", mobileno); + List completedlist=bookingDetailsRepository.findSettlementCompletedList(); + List cancelledcompletedlist=bookingDetailsRepository.findCancelledCompletedList(); + List rejectedcompletedlist=bookingDetailsRepository.findRejectedSettlementCompletedList(); + model.addAttribute("title","settlement initiate"); + model.addAttribute("headquartersname", headquartersname); + model.addAttribute("completedlist",completedlist); + model.addAttribute("cancelledcompletedlist",cancelledcompletedlist); + model.addAttribute("rejectedcompletedlist",rejectedcompletedlist); + return "headquarters/settlement-completed"; + }else { + session.invalidate(); // Invalidate the session to clear all session attributes return "redirect:/communityhall/login"; - } + } } @GetMapping("/settlementlist") @@ -633,6 +638,62 @@ public class HeadquartersController { } } + @GetMapping("/logout") + public String viewLogout(Model model,HttpSession session) { + session.invalidate(); + return "redirect:/communityhall/login"; + } + + @GetMapping("/Gccblocking") + public String viewGccBlocking(Model model, HttpSession session) { + String headquartersname = (String) session.getAttribute("usertype"); + if(headquartersname != null) { + long mobileno = (long) session.getAttribute("mobileno"); + model.addAttribute("mobileno", mobileno); + model.addAttribute("headquartersname", headquartersname); + // Fetch all blocked GCC dates + List gccBlocked = blockingDateRepository.findAllBlocked(); + + // Ensure distinct by hallId, blockingReason, startDate, and endDate + List uniqueGccBlockingDates = gccBlocked.stream() + .filter(distinctByKey(g -> Arrays.asList( + g.getHallId(), + g.getBlockingReason(), + g.getStartDate(), + g.getEndDate()))) + .collect(Collectors.toList()); + + // Map to store the count of blocked halls for each GccBlockingDate + Map hallCountMap = new HashMap<>(); + for (GccBlockingDate blockedDate : uniqueGccBlockingDates) { + // Parse and count unique hall IDs + String hallIds = blockedDate.getHallId(); + if (hallIds != null && !hallIds.isEmpty()) { + Set uniqueHallIds = new HashSet<>(Arrays.asList(hallIds.split(","))); + int hallCount = uniqueHallIds.size(); + hallCountMap.put(blockedDate.getBlockingId(), hallCount); + } else { + hallCountMap.put(blockedDate.getBlockingId(), 0); // No halls blocked + } + } + + // Add attributes to the model for the view + model.addAttribute("gccblocked", uniqueGccBlockingDates); + model.addAttribute("hallCountMap", hallCountMap); + + return "headquarters/gccblocking"; + }else { + session.invalidate(); // Invalidate the session to clear all session attributes + return "redirect:/communityhall/login"; + } + } + + // Utility method to ensure distinct by a key + private static Predicate distinctByKey(Function keyExtractor) { + Set seen = new HashSet<>(); + return t -> seen.add(keyExtractor.apply(t)); + } + @GetMapping("/viewUploadNoc") public String viewUploadNoc(Model model, HttpSession session) { String headquartersname = (String) session.getAttribute("usertype"); @@ -653,11 +714,5 @@ public class HeadquartersController { } } - @GetMapping("/logout") - public String viewLogout(Model model,HttpSession session) { - session.invalidate(); - 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 54133b83..5480e9de 100644 --- a/src/main/java/com/gcc/communityHall/controller/OfficerAPIController.java +++ b/src/main/java/com/gcc/communityHall/controller/OfficerAPIController.java @@ -170,63 +170,62 @@ public class OfficerAPIController { 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" - ) + 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}") public ResponseEntity updateApprovedSettlementStatus( - @PathVariable("settlementId") int settlementId, - @RequestParam("status") BookingDetails.RefundStatus status, - @RequestParam("comments") String comments) { - - try { - // Update settlement status - Settlement updateSettlement = settlementService.updateSettlementStatus(settlementId, status, comments); - if (updateSettlement == null) { - return new ResponseEntity<>(HttpStatus.NOT_FOUND); - } + @PathVariable("settlementId") int settlementId, + @RequestParam("status") BookingDetails.RefundStatus status, + @RequestParam("comments") String comments) { - // 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(updateSettlement.getBookingDetails().getBookingId()); - logs.setLogType("Booking Status: " + status.toString()); - - try { - InetAddress inetAddress = InetAddress.getLocalHost(); - String hostname = InetAddress.getLocalHost().getHostName(); - logs.setIpaddress(inetAddress.getHostAddress()); - logs.setSystemName(hostname); - } catch (UnknownHostException e) { - e.printStackTrace(); - } + try { + // Update settlement status + Settlement updateSettlement = settlementService.updateSettlementStatus(settlementId, status, comments); + if (updateSettlement == null) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } - applicationLogsRepository.save(logs); + // 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(updateSettlement.getBookingDetails().getBookingId()); + logs.setLogType("Booking Status: " + status.toString()); - // Process refund request - String refundResponse = bookingServiceImpl.processRefundRequest(updateSettlement.getBookingDetails().getBookingId()); + try { + InetAddress inetAddress = InetAddress.getLocalHost(); + String hostname = InetAddress.getLocalHost().getHostName(); + logs.setIpaddress(inetAddress.getHostAddress()); + logs.setSystemName(hostname); + } catch (UnknownHostException e) { + e.printStackTrace(); + } - if (refundResponse.contains("successful")) { - // Refund success, return updated settlement and status - return new ResponseEntity<>(updateSettlement, HttpStatus.OK); - } else { - // Refund failure, update refund status to FAILURE - bookingService.updateRefundStatus(updateSettlement.getBookingDetails().getBookingId(), BookingDetails.RefundStatus.FAILURE); - return new ResponseEntity<>("Refund processing failed: " + refundResponse, HttpStatus.INTERNAL_SERVER_ERROR); - } + applicationLogsRepository.save(logs); - } catch (Exception e) { - return new ResponseEntity<>("An error occurred while processing the settlement for Settlement ID: " + settlementId, HttpStatus.INTERNAL_SERVER_ERROR); - } + // Process refund request + String refundResponse = bookingServiceImpl.processRefundRequest(updateSettlement.getBookingDetails().getBookingId()); + + if (refundResponse.contains("successful")) { + // Refund success, return updated settlement and status + return new ResponseEntity<>(updateSettlement, HttpStatus.OK); + } else { + // Refund failure, update refund status to FAILURE + bookingService.updateRefundStatus(updateSettlement.getBookingDetails().getBookingId(), BookingDetails.RefundStatus.FAILURE); + return new ResponseEntity<>("Refund processing failed: " + refundResponse, HttpStatus.INTERNAL_SERVER_ERROR); + } + + } catch (Exception e) { + 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" @@ -308,36 +307,35 @@ public class OfficerAPIController { //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) { + @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; + 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); + } } - @PostMapping("/toggleStatus") public ResponseEntity toggleUserStatus( @RequestParam Integer userId, diff --git a/src/main/java/com/gcc/communityHall/controller/UserAPIController.java b/src/main/java/com/gcc/communityHall/controller/UserAPIController.java index d68a03ac..fcff6671 100644 --- a/src/main/java/com/gcc/communityHall/controller/UserAPIController.java +++ b/src/main/java/com/gcc/communityHall/controller/UserAPIController.java @@ -1,6 +1,7 @@ package com.gcc.communityHall.controller; + import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -27,9 +28,6 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.messaging.handler.annotation.MessageMapping; -import org.springframework.messaging.handler.annotation.SendTo; -import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.ui.Model; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; @@ -45,8 +43,6 @@ import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.thymeleaf.context.Context; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.gcc.communityHall.dto.BookingDetailsDTO; import com.gcc.communityHall.dto.EmployeeDetails; @@ -105,9 +101,7 @@ import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; import lombok.AllArgsConstructor; - import static org.hibernate.query.sqm.tree.SqmNode.log; - import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; @@ -133,137 +127,133 @@ public class UserAPIController { private AppConfig appConfig; @Autowired private UserSession userSession; - @Autowired - private SmsSenderRepository smsSenderRepository; - @Autowired - private BookingCalendarRepository bookingCalendarRepository; - @Autowired - private UserService userservice; - - @Autowired - private BookingService bookingService; - - @Autowired - private UserService userService; - - @Autowired - private CounterService counterservice; - - @Autowired - private BookingDetailsRepository bookingDetailsRepository; - - @Autowired - private BookingHistoryRepository bookingHistoryRepository; - - @Autowired - private CounterService counterService; - - @Autowired - private UserService userServices; - - @Autowired - private HallDetailService hallDetailService; - - @Autowired - private CalendarService calendarService; - - @Autowired - private UsersRepository usersRepository; - - private final String uploadDirectory; - - @Autowired - private WhatsappMsgServiceImpl whatsappMsgServiceImpl; - - @Autowired - private PaymentGatewayServiceImpl PaymentGatewayServiceImpl; - - @Autowired - private TransRefundResRepository transRefundResRepository; - - private final SimpMessagingTemplate messagingTemplate; - - @Autowired - public UserAPIController(@Value("${file.upload.directory}") String uploadDirectory, - SimpMessagingTemplate messagingTemplate, BookingService bookingService) { - this.uploadDirectory = uploadDirectory; - this.messagingTemplate = messagingTemplate; -// this.bookingService = bookingService; - } - - @Operation( - summary = "Retrieving the HallDetails by HallId REST API", - description = "REST API to Retrieving the HallDetails by HallId" - ) - @ApiResponses({ - @ApiResponse( - responseCode = "200", - description = "HTTP Status UPDATED" - ), - @ApiResponse( - responseCode = "500", - description = "HTTP Status Internal Server Error", - content = @Content( - schema = @Schema(implementation = ErrorResponseDto.class) - ) - ) - } - ) - //retrieving Hall Details by HallId - @GetMapping("/gethalldetails/{hallId}") - public ResponseEntity getHallDetails(@PathVariable int hallId) { - Optional hallDetails = hallDetailsRepository.findById(hallId); - return hallDetails.map(ResponseEntity::ok) - .orElseGet(() -> ResponseEntity.status(404).body(null)); - } - - @Operation( - summary = "Retrieving the Hallnames only REST API", - description = "REST API to Retrieving the Hallnames only" - ) - - - @GetMapping("/gethallnames") - public ResponseEntity> getHallNames() { - List hallDetailsList = hallDetailsRepository.findActiveHalls(); - List hallDataList = new ArrayList<>(); - for (HallDetails hallDetails : hallDetailsList) { - HallDetails hallData = new HallDetails(); - hallData.setHallId(hallDetails.getHallId()); - hallData.setHallName(hallDetails.getHallName()); - hallDataList.add(hallData); - } - return ResponseEntity.ok(hallDataList); // Return ResponseEntity with list of HallData objects containing only id and hallname - } - + @Autowired + private SmsSenderRepository smsSenderRepository; + @Autowired + private BookingCalendarRepository bookingCalendarRepository; + @Autowired + private UserService userservice; + + @Autowired + private BookingService bookingService; + + @Autowired + private UserService userService; + + @Autowired + private CounterService counterservice; + + @Autowired + private BookingDetailsRepository bookingDetailsRepository; + + @Autowired + private BookingHistoryRepository bookingHistoryRepository; + + @Autowired + private CounterService counterService; + + @Autowired + private UserService userServices; + + @Autowired + private HallDetailService hallDetailService; + + @Autowired + private CalendarService calendarService; + + @Autowired + private UsersRepository usersRepository; + + private final String uploadDirectory; + + @Autowired + private WhatsappMsgServiceImpl whatsappMsgServiceImpl; + + @Autowired + private PaymentGatewayServiceImpl PaymentGatewayServiceImpl; + + @Autowired + private TransRefundResRepository transRefundResRepository; + + @Autowired + public UserAPIController(@Value("${file.upload.directory}") String uploadDirectory) { + this.uploadDirectory = uploadDirectory; + } + + @Operation( + summary = "Retrieving the HallDetails by HallId REST API", + description = "REST API to Retrieving the HallDetails by HallId" + ) + @ApiResponses({ + @ApiResponse( + responseCode = "200", + description = "HTTP Status UPDATED" + ), + @ApiResponse( + responseCode = "500", + description = "HTTP Status Internal Server Error", + content = @Content( + schema = @Schema(implementation = ErrorResponseDto.class) + ) + ) + } + ) + //retrieving Hall Details by HallId + @GetMapping("/gethalldetails/{hallId}") + public ResponseEntity getHallDetails(@PathVariable int hallId) { + Optional hallDetails = hallDetailsRepository.findById(hallId); + return hallDetails.map(ResponseEntity::ok) + .orElseGet(() -> ResponseEntity.status(404).body(null)); + } + + @Operation( + summary = "Retrieving the Hallnames only REST API", + description = "REST API to Retrieving the Hallnames only" + ) + + + @GetMapping("/gethallnames") + public ResponseEntity> getHallNames() { + List hallDetailsList = hallDetailsRepository.findActiveHalls(); + List hallDataList = new ArrayList<>(); + for (HallDetails hallDetails : hallDetailsList) { + HallDetails hallData = new HallDetails(); + hallData.setHallId(hallDetails.getHallId()); + hallData.setHallName(hallDetails.getHallName()); + hallDataList.add(hallData); + } + return ResponseEntity.ok(hallDataList); // Return ResponseEntity with list of HallData objects containing only id and hallname + } - @Operation( - summary = "Send OTP REST API", - description = "REST API For Sending OTP to user" - ) + + @Operation( + summary = "Send OTP REST API", + description = "REST API For Sending OTP to user" + ) //SendOTP @GetMapping(value = "/sendOTP") - public String sendOtp(HttpServletRequest request, @RequestParam Long mobileNo, @RequestParam String purpose) { + public String sendOtp(HttpServletRequest request, @RequestParam Long mobileNo,@RequestParam String purpose) { - Long MobileNo = mobileNo; + Long MobileNo=mobileNo; //System.out.println(purpose); //System.out.print("\n MobileNo---:"+mobileNo); Random rand = new Random(); - int otp = rand.nextInt(90000) + 10000; - System.out.print("\n otp---:" + otp); +// int otp = rand.nextInt(90000) + 10000; + int otp = 11111; + System.out.print("\n otp---:"+otp); DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MMM-yyyy%20HH:mm"); LocalDateTime now = LocalDateTime.now(); //System.out.println(dtf.format(now)); - String key = "pfTEYN6H"; - String generatedToken = "Welcome to GCC! Your OTP for GCC Community Centre is " + otp; - String urlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + mobileNo + "&from=GCCCRP&body=Welcome to GCC! Your OTP for GCC Community Centre booking is " + otp + "&entityid=1401572690000011081&templateid=1407172346444550398"; + String key="pfTEYN6H"; + String generatedToken = "Welcome to GCC! Your OTP for GCC Community Centre is "+otp; + String urlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to="+mobileNo+"&from=GCCCRP&body=Welcome to GCC! Your OTP for GCC Community Centre booking is "+otp+"&entityid=1401572690000011081&templateid=1407172346444550398"; System.out.println(urlString); - System.out.print("\n urlString---: " + urlString); + System.out.print("\n urlString---: "+urlString); String bodyMessage = ""; - try { + /*try { RestTemplate restTemplate = new RestTemplate(); String Response = restTemplate.getForObject(urlString, String.class); - bodyMessage = Response; + bodyMessage=Response; SmsSender sms = new SmsSender(); sms.setPhone(MobileNo); sms.setCdate(new Date()); @@ -271,26 +261,26 @@ public class UserAPIController { 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 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); + System.out.println("sendwhatsuprepsosne===="+sendMsg); } catch (Exception e) { - // System.out.print("ERROR in Sending---: "+e); + // System.out.print("ERROR in Sending---: "+e); bodyMessage = "Error"; - } + }*/ HttpSession session = request.getSession(); session.setAttribute("otp", otp); return bodyMessage; } - @Operation( - summary = "Vetify OTP REST API", - description = "REST API For verifying OTP" - ) + @Operation( + summary = "Vetify OTP REST API", + description = "REST API For verifying OTP" + ) //VerifyOTP @GetMapping(value = "/verifyOTP") - public String verifyOtp(HttpServletRequest request, @RequestParam String otp, @RequestParam long mobileNo) { + public String verifyOtp(HttpServletRequest request, @RequestParam String otp,@RequestParam long mobileNo) { HttpSession session = request.getSession(); try { Integer session_otp = (Integer) session.getAttribute("otp"); @@ -300,22 +290,22 @@ public class UserAPIController { if (session_otp != null && session_otp.equals(entered_otp)) { System.out.println("Entered OTP Correct user API"); Users user = userservice.findByMobileno(mobileNo); - if (user != null) { - userSession.setMobileno(user.getMobileNo()); - //userSession.setUserType(user.getUserType()); - userSession.setDispayName(user.getName()); - userSession.setUserId(user.getUserId()); - String userType = user.getUsertype().toString(); - userSession.setUserType(userType); + if(user!=null) { + userSession.setMobileno(user.getMobileNo()); + //userSession.setUserType(user.getUserType()); + userSession.setDispayName(user.getName()); + userSession.setUserId(user.getUserId()); + String userType = user.getUsertype().toString(); + userSession.setUserType(userType); } session.setAttribute("verifiedotp", "success"); return "Success"; } else { System.out.println("Incorrect OTP. Please enter correct OTPs."); - session.setAttribute("user", ""); + session.setAttribute("user",""); session.setAttribute("mobileNo", ""); - session.setAttribute("id", ""); + session.setAttribute("id",""); session.setAttribute("verifiedotp", "error"); return "Error"; } @@ -323,161 +313,146 @@ public class UserAPIController { //System.out.println("Invalid OTP format: " + otp); return "Error"; } catch (Exception e) { - // System.out.println("Error verifying OTP: " + e.getMessage()); + // System.out.println("Error verifying OTP: " + e.getMessage()); return "Error"; } } - - @GetMapping(value = "/verifyofficialOTP") - public String verifyOtp(HttpServletRequest request, @RequestParam String otp) { - HttpSession session = request.getSession(); - try { - Integer session_otp = (Integer) session.getAttribute("otp"); + @GetMapping(value = "/verifyofficialOTP") + public String verifyOtp(HttpServletRequest request, @RequestParam String otp) { + HttpSession session = request.getSession(); + try { + Integer session_otp = (Integer) session.getAttribute("otp"); // System.out.println("session_otp---:" + session_otp); - Integer entered_otp = Integer.parseInt(otp); + Integer entered_otp = Integer.parseInt(otp); - if (session_otp != null && session_otp.equals(entered_otp)) { - //System.out.println("Entered OTP Correct"); - session.setAttribute("verifiedotp", "success"); - return "Success"; - } else { + if (session_otp != null && session_otp.equals(entered_otp)) { + //System.out.println("Entered OTP Correct"); + session.setAttribute("verifiedotp", "success"); + return "Success"; + } else { // System.out.println("Incorrect OTP. Please enter correct OTPs."); - session.setAttribute("verifiedotp", "error"); - return "Error"; - } - } catch (NumberFormatException e) { + session.setAttribute("verifiedotp", "error"); + return "Error"; + } + } catch (NumberFormatException e) { // System.out.println("Invalid OTP format: " + otp); - return "Error"; - } catch (Exception e) { - //System.out.println("Error verifying OTP: " + e.getMessage()); - return "Error"; - } - } - - @Operation( - summary = "User Mobileno Validation REST API", - description = "REST API For Validating User with Mobileno" - ) + return "Error"; + } catch (Exception e) { + //System.out.println("Error verifying OTP: " + e.getMessage()); + return "Error"; + } + } + + @Operation( + summary = "User Mobileno Validation REST API", + description = "REST API For Validating User with Mobileno" + ) //Validating User with the mobileno - @GetMapping(value = "/checkMobileExits") - public String checkMobileExits(@RequestParam long mobileno) { - try { - Users form = userservice.findByMobileno(mobileno); - if (form != null) { - return "success"; - } else { - return "error"; - } - } catch (NumberFormatException e) { - // Handle the case where the phone number cannot be parsed as a Long - return "error"; - } catch (Exception e) { - // Handle any other unexpected exceptions - return "error"; - - } - } - - @Operation( - summary = "Cousellor Mobileno Validation REST API", - description = "REST API For Validating the Counsellor Mobileno" - ) - //Counsellor Mobile no Validation - @GetMapping(value = "/checkCounsellorMobileExits") - public ResponseEntity checkCounsellorMobileExits(@RequestParam long mobileno) { - // Find the counsellor by the provided mobile number - Counsellordetails counsellor = userservice.findByMobile(mobileno); // This checks both mobileNo1 and mobileNo2 in the counsellor table - if (counsellor == null) { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Counsellor Mobile Number Not Found"); - } - - // Check if mobileNo1 or mobileNo2 of the counsellor is already used in the Users table - boolean isMobile1Used = usersRepository.existsByMobileNo(counsellor.getMobile1()); - boolean isMobile2Used = usersRepository.existsByMobileNo(counsellor.getMobile2()); - - if (isMobile1Used || isMobile2Used) { - return ResponseEntity.status(HttpStatus.CONFLICT).body("One of the counsellor's mobile numbers is already used."); - } - - // If no conflict, return success with the counsellor's name - return ResponseEntity.ok(counsellor.getName()); - } - - - @GetMapping("/checkEmployee") - public Map checkEmployee(@RequestParam String id) { - boolean isRegistered = usersRepository.existsByGovernmentId(id); - Map response = new HashMap<>(); - response.put("isRegistered", isRegistered); - return response; - } - - - @Operation( - summary = "Retriving the zone REST API", - description = "REST API to Retriev the zone for displaying in Frontend" - ) - //retrieving the zone - @GetMapping(value = "/getZone") - public List> getZone() { - return hallDetailsRepository.getZoneAndDivision(); - } - - @Operation( - summary = "Zones by Hall REST API", - description = "REST API to Retrieve the zone by Hall for displaying in GccBlocking page" - ) - //retrieving the zones by hall - @GetMapping(value = "/hallsbyzone") - public List> getHallsByZone(@RequestParam(required = false) String zones) { - if (zones == null || zones.isEmpty()) { - return hallDetailsRepository.getAllHalls(); - } else { - List zoneList = Arrays.asList(zones.split(",")); - return hallDetailsRepository.getHallsByZones(zoneList); - } - } - - @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); - if (data != null) { - return data; - } - return data; - } + @GetMapping(value = "/checkMobileExits") + public String checkMobileExits(@RequestParam long mobileno) { + try { + Users form = userservice.findByMobileno(mobileno); + if (form != null) { + return "success"; + } else { + return "error"; + } + } catch (NumberFormatException e) { + // Handle the case where the phone number cannot be parsed as a Long + return "error"; + } catch (Exception e) { + // Handle any other unexpected exceptions + return "error"; + + } + } + + @Operation( + summary = "Cousellor Mobileno Validation REST API", + description = "REST API For Validating the Counsellor Mobileno" + ) + //Counsellor Mobile no Validation + @GetMapping(value = "/checkCounsellorMobileExits") + public ResponseEntity checkCounsellorMobileExits(@RequestParam long mobileno) { + // Find the counsellor by the provided mobile number + Counsellordetails counsellor = userservice.findByMobile(mobileno); // This checks both mobileNo1 and mobileNo2 in the counsellor table + if (counsellor == null) { + return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Counsellor Mobile Number Not Found"); + } + + // Check if mobileNo1 or mobileNo2 of the counsellor is already used in the Users table + boolean isMobile1Used = usersRepository.existsByMobileNo(counsellor.getMobile1()); + boolean isMobile2Used = usersRepository.existsByMobileNo(counsellor.getMobile2()); + + if (isMobile1Used || isMobile2Used) { + return ResponseEntity.status(HttpStatus.CONFLICT).body("One of the counsellor's mobile numbers is already used."); + } + + // If no conflict, return success with the counsellor's name + return ResponseEntity.ok(counsellor.getName()); + } + + + + @GetMapping("/checkEmployee") + public Map checkEmployee(@RequestParam String id) { + boolean isRegistered = usersRepository.existsByGovernmentId(id); + Map response = new HashMap<>(); + response.put("isRegistered", isRegistered); + return response; + } + + + @Operation( + summary = "Retriving the zone REST API", + description = "REST API to Retriev the zone for displaying in Frontend" + ) + //retrieving the zone + @GetMapping(value = "/getZone") + public List> getZone() { + return hallDetailsRepository.getZoneAndDivision(); + } - /*@MessageMapping("/getPastData") - @SendTo("/topic/bookingCalendar") - public List getPastData(String payload) throws JsonProcessingException { - ObjectMapper objectMapper = new ObjectMapper(); - JsonNode jsonNode = objectMapper.readTree(payload); - int hall_id = jsonNode.get("hall_id").asInt(); - - List data = bookingService.getPastData(hall_id); - //System.out.println("Broadcasting data for hall_id " + hall_id + ": " + data); - //messagingTemplate.convertAndSend("/topic/bookingCalendar", data); - messagingTemplate.convertAndSend("/topic/bookingCalendar/" + hall_id, data); - - return data; - }*/ - - @Operation( - summary = "Pensioner Details ERP REST API", - description = "REST API to retrieving the Pensioner Details From ERP" - ) - //retrieving the Pensioner Details From ERP - @GetMapping("/PensionerDetail") - public PensionerDetailsResponse getPensionerDetails(@RequestParam("pensionerId") String pensionerId) { - //System.out.println(pensionerId); - RestTemplate restTemplate = new RestTemplate(); - String url = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?serviceId=getPensionerDetailsList&pensionerId=" + pensionerId; + @Operation( + summary = "Zones by Hall REST API", + description = "REST API to Retrieve the zone by Hall for displaying in GccBlocking page" + ) + //retrieving the zones by hall + @GetMapping(value = "/hallsbyzone") + public List> getHallsByZone(@RequestParam(required = false) String zones) { + if (zones == null || zones.isEmpty()) { + return hallDetailsRepository.getAllHalls(); + } else { + List zoneList = Arrays.asList(zones.split(",")); + return hallDetailsRepository.getHallsByZones(zoneList); + } + } + + @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); + if(data!=null) { + return data; + } + return data; + } + + @Operation( + summary = "Pensioner Details ERP REST API", + description = "REST API to retrieving the Pensioner Details From ERP" + ) + //retrieving the Pensioner Details From ERP + @GetMapping("/PensionerDetail") + public PensionerDetailsResponse getPensionerDetails(@RequestParam("pensionerId") String pensionerId) { + //System.out.println(pensionerId); + RestTemplate restTemplate = new RestTemplate(); + String url = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?serviceId=getPensionerDetailsList&pensionerId="+pensionerId; ResponseEntity responseEntity = restTemplate.getForEntity(url, String.class); @@ -488,7 +463,7 @@ public class UserAPIController { // Extract the Java object from the response body ObjectMapper objectMapper = new ObjectMapper(); try { - PensionerDetailsResponse pensionerResponse = objectMapper.readValue(jsonString, PensionerDetailsResponse.class); + PensionerDetailsResponse pensionerResponse = objectMapper.readValue(jsonString, PensionerDetailsResponse.class); // Now you can access the pensionerResponse object as usual // e.g., pensionerResponse.getPensioners() to get the list of pensioners @@ -501,17 +476,17 @@ public class UserAPIController { } //return null; - } - - @Operation( - summary = "Employee Details ERP REST API", - description = "REST API to retrieving the Employee Details From ERP" - ) - @GetMapping("/EmployeeDetails") - public EmployeeDetailsResponse getEmployeeDetails(@RequestParam("employeeId") Long employeeId) { - //System.out.println("Employee ID:"+employeeId); - RestTemplate restTemplate = new RestTemplate(); - String url = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?serviceId=getEmployeeDetail&EmployeeID=" + employeeId; + } + + @Operation( + summary = "Employee Details ERP REST API", + description = "REST API to retrieving the Employee Details From ERP" + ) + @GetMapping("/EmployeeDetails") + public EmployeeDetailsResponse getEmployeeDetails(@RequestParam("employeeId") Long employeeId) { + //System.out.println("Employee ID:"+employeeId); + RestTemplate restTemplate = new RestTemplate(); + String url = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?serviceId=getEmployeeDetail&EmployeeID="+employeeId; ResponseEntity responseEntity = restTemplate.getForEntity(url, String.class); @@ -535,17 +510,17 @@ public class UserAPIController { } //return null; - } + } - @Operation( - summary = "FamilyPensioner Details ERP REST API", - description = "REST API to retrieving the FamilyPensioner Details From ERP" - ) - //retrieving the FamilyPensionerDetails Details From ERP - @GetMapping("/FamilyPensionerDetail") - public FamilyPensionerDetailsResponse getFamilyPensionerDetails(@RequestParam("id") Long id) { - RestTemplate restTemplate = new RestTemplate(); - String url = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?serviceId=getFamPensionerDetailsList&familPensionId=" + id; + @Operation( + summary = "FamilyPensioner Details ERP REST API", + description = "REST API to retrieving the FamilyPensioner Details From ERP" + ) + //retrieving the FamilyPensionerDetails Details From ERP + @GetMapping("/FamilyPensionerDetail") + public FamilyPensionerDetailsResponse getFamilyPensionerDetails(@RequestParam("id") Long id) { + RestTemplate restTemplate = new RestTemplate(); + String url = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?serviceId=getFamPensionerDetailsList&familPensionId="+id; ResponseEntity responseEntity = restTemplate.getForEntity(url, String.class); @@ -567,14 +542,14 @@ public class UserAPIController { e.printStackTrace(); return null; } - } - - @Operation( - summary = "Hall Details coordinates REST API", - description = "REST API to retrieving the Hall Details coordinates for Map" - ) - //retrieving the All Hall Details coordinates - @GetMapping("/getallhallcoordinates") + } + + @Operation( + summary = "Hall Details coordinates REST API", + description = "REST API to retrieving the Hall Details coordinates for Map" + ) + //retrieving the All Hall Details coordinates + @GetMapping("/getallhallcoordinates") public List> getAllHallCoordinates() { List allHallDetails = hallDetailsRepository.findActiveHalls(); return allHallDetails.stream().map(this::extractRequiredDetails).collect(Collectors.toList()); @@ -582,12 +557,12 @@ public class UserAPIController { private Map extractRequiredDetails(HallDetails hallDetails) { Map details = new HashMap<>(); - + details.put("latitude", hallDetails.getLatitude()); details.put("longitude", hallDetails.getLongitude()); details.put("hallId", String.valueOf(hallDetails.getHallId())); details.put("hallName", hallDetails.getHallName()); - details.put("seatingCapacity", String.valueOf(hallDetails.getSeatingCapacity())); + details.put("seatingCapacity",String.valueOf(hallDetails.getSeatingCapacity()) ); details.put("parkingCapacity", hallDetails.getParkingCapacity()); details.put("hallImage", hallDetails.getHallImagesList()); details.put("fullDayRent", hallDetails.getFullDayRent()); @@ -596,35 +571,35 @@ public class UserAPIController { details.put("area", hallDetails.getArea()); details.put("street", hallDetails.getStreet()); details.put("landMark", hallDetails.getLandMark()); - details.put("doorNo", hallDetails.getDoorNo()); - details.put("hallArea", hallDetails.getHallArea()); + details.put("doorNo", hallDetails.getDoorNo()); + details.put("hallArea", hallDetails.getHallArea()); return details; } - + @Operation( summary = "Booking Limitation Details ERP REST API", description = "REST API to check the Booking Limitation & UserStatus pending" ) - //Booking Limitation & UserStatus pending + //Booking Limitation & UserStatus pending @GetMapping("/bookingLimit") public String CheckbookingLimitation(Model model) { - int userId = userSession.getUserId(); - Users userById = userService.getUserById(userId); - if (userById != null && userById.getUserstatus() == Users.userStatus.PENDING) { - return "pending"; - } - if (userById != null && userById.getUserstatus() == Users.userStatus.REJECTED) { - return "rejected"; - } + int userId = userSession.getUserId(); + Users userById = userService.getUserById(userId); + if(userById!=null && userById.getUserstatus()==Users.userStatus.PENDING) { + return "pending"; + } + if (userById != null && userById.getUserstatus() == Users.userStatus.REJECTED) { + return "rejected"; + } int checkUserBookingLimitation = bookingService.checkUserBookinglimitation(userId); - // System.out.println("checkUserBookingLimitation="+checkUserBookingLimitation); +// System.out.println("checkUserBookingLimitation="+checkUserBookingLimitation); if (checkUserBookingLimitation < 2) { - //System.out.println("checkUserBookingLimitationss="+checkUserBookingLimitation); +// System.out.println("checkUserBookingLimitationss="+checkUserBookingLimitation); return "success"; } return "failure"; } - + @Operation( summary = "Counter Booikng Limit REST API", description = "REST API to check the Counter Booking Limitation" @@ -634,20 +609,20 @@ public class UserAPIController { Users user = userService.getUserDetailsByMobileNo(mobileNo); if (user == null) { - // System.err.println("User not found for mobile number: " + mobileNo); + // System.err.println("User not found for mobile number: " + mobileNo); return "checkmobilenoexists"; // You can return a different status or handle it accordingly } int userId = user.getUserId(); int checkUserBookingLimitation = bookingService.checkUserBookinglimitation(userId); - + if (checkUserBookingLimitation >= 2) { - // System.err.println("bookinglimitreached"); + // System.err.println("bookinglimitreached"); return "bookinglimitreached"; } if (user != null && !user.isActive()) { return "deactive"; } - + return "checkmobilenoexists"; } @@ -679,15 +654,15 @@ public class UserAPIController { userDetails.put("displayName", userSession.getDispayName()); userDetails.put("mobileNo", userSession.getMobileno()); userDetails.put("userType", userSession.getUserType()); - + return ResponseEntity.ok(userDetails); } - + @GetMapping(value = "/getZonehalls") public List> getZonehalls() { return hallDetailsRepository.getZonesAndDivisions(); } - + @Operation( summary = "ZONES from ERP REST API", description = "REST API to get the zones from ERP" @@ -696,7 +671,7 @@ public class UserAPIController { @GetMapping(value = "/getZoneNo") public String getZoneNo() { - String urlString = appConfig.getErpUrl() + "serviceId=getZones"; + String urlString = appConfig.getErpUrl()+"serviceId=getZones"; ResponseEntity response = null; RestTemplate restTemplate = new RestTemplate(); String bodyMessage = ""; @@ -721,7 +696,7 @@ public class UserAPIController { // Rest Api From ERP for getting Divisions @GetMapping(value = "/getDiv") public String getDiv(@RequestParam String zoneId) { - String urlString = appConfig.getErpUrl() + "serviceId=getWards&Zoneid=" + zoneId + ""; + String urlString = appConfig.getErpUrl()+"serviceId=getWards&Zoneid="+zoneId+""; ResponseEntity response = null; RestTemplate restTemplate = new RestTemplate(); String bodyMessage = ""; @@ -739,7 +714,7 @@ public class UserAPIController { } return bodyMessage; } - + @Operation( summary = "HAlls By Division ERP REST API", description = "REST API to get the HAlls by Divisions" @@ -749,7 +724,7 @@ public class UserAPIController { public List getHallsByDivision(@RequestParam("division") String division) { return hallDetailsRepository.findByDivision(division); } - + @Operation( summary = "HAlls By zone ERP REST API", description = "REST API to get the HAlls by zone" @@ -758,7 +733,7 @@ public class UserAPIController { public List getHallsByzone(@RequestParam("zone") String zone) { return hallDetailsRepository.findByZone(zone); } - + @Operation( summary = "Booking Details By bookingId ERP REST API", description = "REST API to get the Booking Details based on BookingId" @@ -773,22 +748,22 @@ public class UserAPIController { return ResponseEntity.notFound().build(); } } - + @Operation( summary = "New Registration in Counter REST API", description = "REST API for New Registration in Counter" ) - //New Registration in Counter + //New Registration in Counter @PostMapping("/newcounterregistrationform") public ResponseEntity showRegistrationForm( @ModelAttribute Users counterform, @RequestParam(value = "userPhoto", required = false) MultipartFile userPhoto) { - + try { if (userPhoto != null && !userPhoto.isEmpty()) { counterform.setUserPhoto(userPhoto); // Set the photo if it exists } - + Users user = userService.user(counterform); userSession.setMobileno(user.getMobileNo()); userSession.setDispayName(user.getName()); @@ -811,114 +786,114 @@ public class UserAPIController { } } - + @Operation( summary = "Counter User Details REST API", description = "REST API to get the User Details by Mobileno for counter" ) - //retrieving the User Details by Mobileno for Counter - @GetMapping("/getUserDetails") - public ResponseEntity getUserDetailsByMobileNo(@RequestParam("mobileNo") long mobileNo) { - try { - // Call service method to retrieve user details by mobile number - Users userDetails = userService.getUserDetailsByMobileNo(mobileNo); - if (userDetails != null) { - return ResponseEntity.ok(userDetails); - } else { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("User not found"); - } - } catch (Exception e) { - // Log the exception and return an appropriate error response - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error retrieving user details"); - } - } - + //retrieving the User Details by Mobileno for Counter + @GetMapping("/getUserDetails") + public ResponseEntity getUserDetailsByMobileNo(@RequestParam("mobileNo") long mobileNo) { + try { + // Call service method to retrieve user details by mobile number + Users userDetails = userService.getUserDetailsByMobileNo(mobileNo); + if (userDetails != null) { + return ResponseEntity.ok(userDetails); + } else { + return ResponseEntity.status(HttpStatus.NOT_FOUND).body("User not found"); + } + } catch (Exception e) { + // Log the exception and return an appropriate error response + e.printStackTrace(); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error retrieving user details"); + } + } + @Operation( summary = "DD Image by CounterID REST API", description = "REST API to get the DD Image by counterId" ) - //retrieving the Dd Image by counterId - @GetMapping("/getImageByDdId") - public ResponseEntity getImageByDdId(@RequestParam int counterId) { - CounterDetails counterDetails = counterservice.getDdImageById(counterId); - if (counterDetails != null) { - //System.out.println("CounterDetails found: " + counterDetails.getDdphoto()); - return ResponseEntity.ok(counterDetails); - } else { - //System.out.println("CounterDetails not found for ID: " + counterId); - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); - } - } - + //retrieving the Dd Image by counterId + @GetMapping("/getImageByDdId") + public ResponseEntity getImageByDdId(@RequestParam int counterId) { + CounterDetails counterDetails = counterservice.getDdImageById(counterId); + if (counterDetails != null) { + //System.out.println("CounterDetails found: " + counterDetails.getDdphoto()); + return ResponseEntity.ok(counterDetails); + } else { + //System.out.println("CounterDetails not found for ID: " + counterId); + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); + } + } + @Operation( summary = "Counter Booking Cancellation by Letter and Reason REST API", description = "REST API save the counter Booking Cancellation Letter and reason" ) - //Saving the counter Booking Cancellation Letter and reason - @PostMapping("/saveCancellation") - public ResponseEntity saveCancellation( - @RequestParam("counterId") int counterId, - @RequestParam("uploadLetter") MultipartFile uploadLetter, - @RequestParam("reason") String reason) throws IOException { - - //System.out.println("Received counterId: " + counterId); - //System.out.println("Received file: " + uploadLetter.getOriginalFilename()); - - // Fetch booking details using counterId - List bookingList = bookingDetailsRepository.findByCounterId(counterId); - - if (bookingList.isEmpty()) { - //System.out.println("No bookings found for counterId: " + counterId); - } - - for (BookingDetails booking : bookingList) { - booking.setBookingStatus(BookingStatus.CANCELED); - bookingDetailsRepository.save(booking); - - List bookingCalendarList = bookingCalendarRepository.getCancellingdata1(String.valueOf(booking.getBookingId())); - - for (BookingCalendar calendar : bookingCalendarList) { - boolean isUpdated = false; - - if (String.valueOf(booking.getBookingId()).equals(calendar.getBookingId_1())) { - calendar.setBookingId_1(null); - isUpdated = true; - } - if (String.valueOf(booking.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); - } - } - } - CounterRefundList counterRefundList = counterservice.saveCancellation(counterId, uploadLetter, reason); - - return ResponseEntity.ok(counterRefundList); - } + //Saving the counter Booking Cancellation Letter and reason + @PostMapping("/saveCancellation") + public ResponseEntity saveCancellation( + @RequestParam("counterId") int counterId, + @RequestParam("uploadLetter") MultipartFile uploadLetter, + @RequestParam("reason") String reason) throws IOException { + + //System.out.println("Received counterId: " + counterId); + //System.out.println("Received file: " + uploadLetter.getOriginalFilename()); + + // Fetch booking details using counterId + List bookingList = bookingDetailsRepository.findByCounterId(counterId); + + if (bookingList.isEmpty()) { + //System.out.println("No bookings found for counterId: " + counterId); + } + + for (BookingDetails booking : bookingList) { + booking.setBookingStatus(BookingStatus.CANCELED); + bookingDetailsRepository.save(booking); + + List bookingCalendarList = bookingCalendarRepository.getCancellingdata1(String.valueOf(booking.getBookingId())); + + for (BookingCalendar calendar : bookingCalendarList) { + boolean isUpdated = false; + + if (String.valueOf(booking.getBookingId()).equals(calendar.getBookingId_1())) { + calendar.setBookingId_1(null); + isUpdated = true; + } + if (String.valueOf(booking.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); + } + } + } + CounterRefundList counterRefundList = counterservice.saveCancellation(counterId, uploadLetter, reason); + + return ResponseEntity.ok(counterRefundList); + } @Operation( summary = "Counter Booking Details by CounterId REST API", description = "REST API to get the Counter Details by CounterId" ) - //retrieving Counter Booking Details by counterId - @GetMapping("/counterdetails") - public List getUserDetailsbycounterId(@RequestParam("counterId") int counterId) { - List counterRefundList = bookingDetailsRepository.getCounterDetailsbycounterId(counterId); - return counterRefundList; - } + //retrieving Counter Booking Details by counterId + @GetMapping("/counterdetails") + public List getUserDetailsbycounterId(@RequestParam("counterId") int counterId) { + List counterRefundList = bookingDetailsRepository.getCounterDetailsbycounterId(counterId); + return counterRefundList; + } // @GetMapping("/getUser") @@ -928,12 +903,12 @@ public class UserAPIController { // } // return ResponseEntity.ok(userService.getUserById(userId)); // } - + @Operation( summary = "Updating the User Details Mobileno Validation REST API", description = "REST API to Update the User Details if the User status is Rejected" ) - //Updating the Rejected user details + //Updating the Rejected user details @PostMapping("/updateUserDetails") public String updateUserDetails( @RequestParam("userId") int userId, @@ -942,8 +917,8 @@ public class UserAPIController { @RequestParam(value = "area", required = false) String area, @RequestParam(value = "location", required = false) String location, @RequestParam(value = "usertype", required = false) String userType, - @RequestParam(value = "pinCode", required = false) int pinCode, - @RequestParam(value = "email", required = false) String email, + @RequestParam(value="pinCode", required = false) int pinCode, + @RequestParam(value="email", required = false) String email, @RequestParam(value = "profilephoto", required = false) MultipartFile profilephoto) { Users userDetails = new Users(); @@ -987,614 +962,740 @@ public class UserAPIController { return userServices.updateUserDetails(userDetails); } - + @Operation( summary = "Counter User Details REST API", description = "REST API to Get the User Details for Counter" ) - //Retrive user details for counter - @GetMapping("/getuserforcounter") - public ResponseEntity getCounterUserById(@RequestParam int userId) { - if (userId == 0) { - userId = userSession.getUserId(); - // System.out.println("User ID retrieved from session: " + userId); - } else { - //System.out.println("User ID provided as parameter: " + userId); - } - - Users user = userService.getUserById(userId); - if (user == null) { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("User not found"); - } - return ResponseEntity.ok(user); - } + //Retrive user details for counter + @GetMapping("/getuserforcounter") + public ResponseEntity getCounterUserById(@RequestParam int userId){ + if(userId == 0) { + userId = userSession.getUserId(); + // System.out.println("User ID retrieved from session: " + userId); + } else { + //System.out.println("User ID provided as parameter: " + userId); + } + + Users user = userService.getUserById(userId); + if(user == null) { + return ResponseEntity.status(HttpStatus.NOT_FOUND).body("User not found"); + } + return ResponseEntity.ok(user); + } @Operation( summary = "User Details REST API", description = "REST API to Get the User Details" ) - //retrieving User Details - @GetMapping("/getUser") - public ResponseEntity getUserByID(@RequestParam int userId) { - if (userId == 0) { - userId = userSession.getUserId(); - } - Users user = userService.getUserById(userId); - Map response = new HashMap<>(); - response.put("userId", user.getUserId()); - response.put("name", user.getName()); - response.put("email", user.getEmail()); - response.put("mobileNo", user.getMobileNo()); - response.put("doorNo", user.getDoorNo()); - response.put("area", user.getArea()); - response.put("location", user.getLocation()); - response.put("pinCode", user.getPinCode()); - response.put("userstatus", user.getUserstatus()); - response.put("profilephoto", user.getProfilephoto()); - response.put("usertype", user.getUsertype()); - - if ("REJECTED".equalsIgnoreCase(user.getUserstatus().name())) { - List histories = user.getUserHistories(); - String rejectionReason = histories.stream() - .filter(history -> history.getComments() != null) - .map(UserHistory::getComments) - .findFirst() - .orElse("No reason provided"); - response.put("rejectionReason", rejectionReason); - } - - //System.out.println("Response: " + response); // Log the response - return ResponseEntity.ok(response); - } + //retrieving User Details + @GetMapping("/getUser") + public ResponseEntity getUserByID(@RequestParam int userId) { + if (userId == 0) { + userId = userSession.getUserId(); + } + Users user = userService.getUserById(userId); + Map response = new HashMap<>(); + response.put("userId",user.getUserId()); + response.put("name", user.getName()); + response.put("email", user.getEmail()); + response.put("mobileNo", user.getMobileNo()); + response.put("doorNo", user.getDoorNo()); + response.put("area", user.getArea()); + response.put("location", user.getLocation()); + response.put("pinCode", user.getPinCode()); + response.put("userstatus", user.getUserstatus()); + response.put("profilephoto", user.getProfilephoto()); + response.put("usertype", user.getUsertype()); + + if ("REJECTED".equalsIgnoreCase(user.getUserstatus().name())) { + List histories = user.getUserHistories(); + String rejectionReason = histories.stream() + .filter(history -> history.getComments() != null) + .map(UserHistory::getComments) + .findFirst() + .orElse("No reason provided"); + response.put("rejectionReason", rejectionReason); + } + + //System.out.println("Response: " + response); // Log the response + return ResponseEntity.ok(response); + } @Operation( summary = "Saving the Booking Details REST API", description = "REST API to Save the Booking Details" ) - //APi for Saving the Booking Details - @PostMapping(path = "/saveTheRequest2", consumes = {"multipart/form-data"}) - public ResponseEntity saveTheBookingDetails2(HttpServletRequest request) { - MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; - Map bookingDetails = splitFormData(multipartRequest); -// System.out.println("Bc Id 1..............."+bookingDetails.get("bcId")); - Map saveBookingDetails = bookingService.saveBookingDetails(bookingDetails); - return ResponseEntity.ok(saveBookingDetails); - } - - public Map splitFormData(MultipartHttpServletRequest multipartRequest) { - Map formData = new HashMap<>(); - - // Iterate through the request parameters - Enumeration parameterNames = multipartRequest.getParameterNames(); - while (parameterNames.hasMoreElements()) { - String paramName = parameterNames.nextElement(); - String paramValues = multipartRequest.getParameter(paramName); - formData.put(paramName, paramValues); - } - - // Iterate through the request parts (files) - try { - Map fileMap = multipartRequest.getFileMap(); - for (Map.Entry entry : fileMap.entrySet()) { - MultipartFile file = entry.getValue(); - if (!file.isEmpty()) { - formData.put(entry.getKey(), file); - } - } - } catch (Exception e) { - e.printStackTrace(); // Handle the exception according to your needs - } - return formData; - } - - @Operation( - summary = "Retrieving the Booking Details by BookingId REST API", - description = "REST API to get the Booking Details by Booking Id" - ) - //retrieving the Booking Details BY Booking ID - @GetMapping("/getBooking") - public ResponseEntity getBookingByID(@RequestParam int bookingId) { - return ResponseEntity.ok(bookingService.getBookingsById(bookingId)); - } - - @Operation( - summary = "User Booking Cancelling by BookingId REST API", - description = "REST API to Cancel the Booking by BookingId by User" - ) - //Booking Cancelling by BookingId + //APi for Saving the Booking Details + @PostMapping(path = "/saveTheRequest2", consumes = { "multipart/form-data" }) + public ResponseEntity saveTheBookingDetails2(HttpServletRequest request) { + MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; + Map bookingDetails = splitFormData(multipartRequest); + Map saveBookingDetails = bookingService.saveBookingDetails(bookingDetails); + return ResponseEntity.ok(saveBookingDetails); + } + + public Map splitFormData(MultipartHttpServletRequest multipartRequest){ + Map formData = new HashMap<>(); + + // Iterate through the request parameters + Enumeration parameterNames = multipartRequest.getParameterNames(); + while (parameterNames.hasMoreElements()) { + String paramName = parameterNames.nextElement(); + String paramValues = multipartRequest.getParameter(paramName); + formData.put(paramName, paramValues); + } + + // Iterate through the request parts (files) + try { + Map fileMap = multipartRequest.getFileMap(); + for (Map.Entry entry : fileMap.entrySet()) { + MultipartFile file = entry.getValue(); + if (!file.isEmpty()) { + formData.put(entry.getKey(), file); + } + } + } catch (Exception e) { + e.printStackTrace(); // Handle the exception according to your needs + } + return formData; + } + + @Operation( + summary = "Retrieving the Booking Details by BookingId REST API", + description = "REST API to get the Booking Details by Booking Id" + ) + //retrieving the Booking Details BY Booking ID + @GetMapping("/getBooking") + public ResponseEntity getBookingByID(@RequestParam int bookingId){ + return ResponseEntity.ok(bookingService.getBookingsById(bookingId)); + } + + @Operation( + summary = "User Booking Cancelling by BookingId REST API", + description = "REST API to Cancel the Booking by BookingId by User" + ) + //Booking Cancelling by BookingId //Booking Cancelling by BookingId - @GetMapping("/cancelBookingbyId") - public ResponseEntity cancelBooking(@RequestParam int bookingId, - @RequestParam BookingDetails.BookingStatus status, - @RequestParam String comments) { - log.info("Received request to cancel booking with ID: {}"); - log.info("Status: {}, Comments: {}"); - Optional bookings = bookingDetailsRepository.findById(bookingId); - BookingDetails bookingDetails = bookings.get(); - try { - BookingDetails cancelledBooking = bookingService.updateCancelledBookingStatus(bookingId, status, comments); - - String cancelledbookingsms = "Your booking ID " + bookingId + " on " + bookingDetails.getStartDate() + " has been cancelled successfully. The deposit amount will be refunded to your account within 3 to 15 days. Thanks for using the GCC Community Hall Booking System."; - String cancelledurlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + bookingDetails.getUsers().getMobileNo() + "&from=GCCCRP&body=" + cancelledbookingsms + "&entityid=1401572690000011081&templateid=1407172346829376988"; - String cancelledwhatsupmsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + bookingDetails.getUsers().getMobileNo() + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+booking+with+ID+" + bookingId + "+on+" + bookingDetails.getStartDate() + "+has+been+cancelled+successfully.+%0AThe+deposit+amount+will+be+refunded+to+your+account+within+3+to+15+days."; - whatsappMsgServiceImpl.sendMsg(cancelledwhatsupmsg); - whatsappMsgServiceImpl.sendSMS(cancelledurlString); - Optional book = bookingDetailsRepository.findById(bookingDetails.getBookingId()); - BookingDetails booking = book.get(); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); - String formattedDate = LocalDateTime.now().format(formatter); - booking.setUpdatedDate(formattedDate); - bookingDetailsRepository.save(booking); - log.info("Booking cancelled successfully"); - return ResponseEntity.ok(cancelledBooking); - } catch (Exception e) { - log.error("Error cancelling booking", e); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body("Error cancelling booking: " + e.getMessage()); - } - } - - @Operation( - summary = "Family Pensioner Details from ERP REST API", - description = "REST API to check the Family Pensioner Details From ERP" - ) - //checking Family pensioner Details - @GetMapping("/FamilyPensionerDetails") - @ResponseBody // Ensure Spring treats the returned object as the response body - public Map getFamilyPensionerDetails(HttpServletRequest request, @RequestParam("id") Long id) { - String purpose = "Checking Pensioner"; - RestTemplate restTemplate = new RestTemplate(); - String url = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?serviceId=getFamPensionerDetailsList&familPensionId=" - + id; - - ResponseEntity responseEntity = restTemplate.getForEntity(url, String.class); - - // Extract the JSON string from the response body - String jsonString = responseEntity.getBody(); - - // Extract the Java object from the response body - ObjectMapper objectMapper = new ObjectMapper(); - Map responseMap = new HashMap<>(); - - try { - FamilyPensionerDetailsResponse familyPensionerDetailsResponse = objectMapper.readValue(jsonString, - FamilyPensionerDetailsResponse.class); - - if (familyPensionerDetailsResponse != null) { - List familyPensionerDetails = familyPensionerDetailsResponse - .getFamilyPensionerDetails(); - - if (familyPensionerDetails != null && !familyPensionerDetails.isEmpty()) { - //Long mobileNo = Long.parseLong(familyPensionerDetailsResponse.getFamilyPensionerDetails().get(0).getMobile_no()); - - Long mobileNo = 8220798937l; - //System.out.println("step 1"); - responseMap.put("mobileNo", mobileNo); - } - } - } catch (IOException e) { - e.printStackTrace(); - } - - return responseMap; - } - - @Operation( - summary = "GCC Employee Details ERP REST API", - description = "REST API to retrieving the GCC Employee Details From ERP" - ) - @GetMapping("/gccemployee") - @ResponseBody // Ensure Spring treats the returned object as the response body - public Map getGccEmployee(HttpServletRequest request, @RequestParam("id") Long id) { - String purpose = "Checking GccEmployee"; - RestTemplate restTemplate = new RestTemplate(); - String url = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?serviceId=getEmployeeDetail&EmployeeID=" - + id; - - ResponseEntity responseEntity = restTemplate.getForEntity(url, String.class); - - // Extract the JSON string from the response body - String jsonString = responseEntity.getBody(); - - // Extract the Java object from the response body - ObjectMapper objectMapper = new ObjectMapper(); - Map responseMap = new HashMap<>(); - - try { - EmployeeDetailsResponse employeeDetailsResponse = objectMapper.readValue(jsonString, - EmployeeDetailsResponse.class); - - if (employeeDetailsResponse != null) { - List employeeDetails = employeeDetailsResponse - .getEmployeeDetailsResult(); - - if (employeeDetails != null && !employeeDetails.isEmpty()) { - //Long mobileNo = Long.parseLong(familyPensionerDetailsResponse.getFamilyPensionerDetails().get(0).getMobile_no()); - - //Long mobileNo = 8220798933l; - //System.out.println("step 1"); - responseMap.put("EmployeeDetailsResult", employeeDetails); - } else { - responseMap.put("EmployeeDetailsResult", null); - } - } - } catch (IOException e) { - e.printStackTrace(); - } - - return responseMap; - } - - @Operation( - summary = "Pensioner Details ERP REST API", - description = "REST API to retrieving the Pensioner Details From ERP" - ) - //checking pensioner Details - @GetMapping("/PensionerDetails") - @ResponseBody - public Map getPensionerDetails(HttpServletRequest request, @RequestParam("id") Long id) { - String purpose = "Checking Employee"; - RestTemplate restTemplate = new RestTemplate(); - String url = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?serviceId=getPensionerDetailsList&pensionerId=" + id; - - ResponseEntity responseEntity = restTemplate.getForEntity(url, String.class); - - // Extract the JSON string from the response body - String jsonString = responseEntity.getBody(); - - // Extract the Java object from the response body - ObjectMapper objectMapper = new ObjectMapper(); - Map responseMap = new HashMap<>(); - - try { - PensionerDetailsResponse pensionerDetailsResponse = objectMapper.readValue(jsonString, PensionerDetailsResponse.class); - - if (pensionerDetailsResponse != null) { - List pensionerDetails = pensionerDetailsResponse.getEmployees(); - - if (pensionerDetails != null && !pensionerDetails.isEmpty()) { - Long mobileNo = Long.parseLong(pensionerDetailsResponse.getEmployees().get(0).getMobile_no()); +@GetMapping("/cancelBookingbyId") + public ResponseEntity cancelBooking(@RequestParam int bookingId, + @RequestParam BookingDetails.BookingStatus status, + @RequestParam String comments) { + log.info("Received request to cancel booking with ID: {}"); + log.info("Status: {}, Comments: {}"); + Optional bookings=bookingDetailsRepository.findById(bookingId); + BookingDetails bookingDetails=bookings.get(); + try { + BookingDetails cancelledBooking = bookingService.updateCancelledBookingStatus(bookingId, status, comments); + + String cancelledbookingsms="Your booking ID "+bookingId+" on "+bookingDetails.getStartDate()+" has been cancelled successfully. The deposit amount will be refunded to your account within 3 to 15 days. Thanks for using the GCC Community Hall Booking System."; + String cancelledurlString ="https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to="+bookingDetails.getUsers().getMobileNo()+"&from=GCCCRP&body="+cancelledbookingsms+"&entityid=1401572690000011081&templateid=1407172346829376988"; + String cancelledwhatsupmsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to="+bookingDetails.getUsers().getMobileNo()+"&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+booking+with+ID+"+bookingId+"+on+"+bookingDetails.getStartDate()+"+has+been+cancelled+successfully.+%0AThe+deposit+amount+will+be+refunded+to+your+account+within+3+to+15+days."; + whatsappMsgServiceImpl.sendMsg(cancelledwhatsupmsg); + whatsappMsgServiceImpl.sendSMS(cancelledurlString); + Optional book=bookingDetailsRepository.findById(bookingDetails.getBookingId()); + BookingDetails booking=book.get(); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + String formattedDate = LocalDateTime.now().format(formatter); + booking.setUpdatedDate(formattedDate); + bookingDetailsRepository.save(booking); + log.info("Booking cancelled successfully"); + return ResponseEntity.ok(cancelledBooking); + } catch (Exception e) { + log.error("Error cancelling booking", e); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body("Error cancelling booking: " + e.getMessage()); + } +} + + @Operation( + summary = "Family Pensioner Details from ERP REST API", + description = "REST API to check the Family Pensioner Details From ERP" + ) + //checking Family pensioner Details + @GetMapping("/FamilyPensionerDetails") + @ResponseBody // Ensure Spring treats the returned object as the response body + public Map getFamilyPensionerDetails(HttpServletRequest request, @RequestParam("id") Long id) { + String purpose = "Checking Pensioner"; + RestTemplate restTemplate = new RestTemplate(); + String url = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?serviceId=getFamPensionerDetailsList&familPensionId=" + + id; + + ResponseEntity responseEntity = restTemplate.getForEntity(url, String.class); + + // Extract the JSON string from the response body + String jsonString = responseEntity.getBody(); + + // Extract the Java object from the response body + ObjectMapper objectMapper = new ObjectMapper(); + Map responseMap = new HashMap<>(); + + try { + FamilyPensionerDetailsResponse familyPensionerDetailsResponse = objectMapper.readValue(jsonString, + FamilyPensionerDetailsResponse.class); + + if (familyPensionerDetailsResponse != null) { + List familyPensionerDetails = familyPensionerDetailsResponse + .getFamilyPensionerDetails(); + + if (familyPensionerDetails != null && !familyPensionerDetails.isEmpty()) { + //Long mobileNo = Long.parseLong(familyPensionerDetailsResponse.getFamilyPensionerDetails().get(0).getMobile_no()); + + Long mobileNo = 8220798937l; + //System.out.println("step 1"); + responseMap.put("mobileNo", mobileNo); + } + } + } catch (IOException e) { + e.printStackTrace(); + } + + return responseMap; + } + + @Operation( + summary = "GCC Employee Details ERP REST API", + description = "REST API to retrieving the GCC Employee Details From ERP" + ) + @GetMapping("/gccemployee") + @ResponseBody // Ensure Spring treats the returned object as the response body + public Map getGccEmployee(HttpServletRequest request, @RequestParam("id") Long id) { + String purpose = "Checking GccEmployee"; + RestTemplate restTemplate = new RestTemplate(); + String url = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?serviceId=getEmployeeDetail&EmployeeID=" + + id; + + ResponseEntity responseEntity = restTemplate.getForEntity(url, String.class); + + // Extract the JSON string from the response body + String jsonString = responseEntity.getBody(); + + // Extract the Java object from the response body + ObjectMapper objectMapper = new ObjectMapper(); + Map responseMap = new HashMap<>(); + + try { + EmployeeDetailsResponse employeeDetailsResponse = objectMapper.readValue(jsonString, + EmployeeDetailsResponse.class); + + if (employeeDetailsResponse != null) { + List employeeDetails = employeeDetailsResponse + .getEmployeeDetailsResult(); + + if (employeeDetails != null && !employeeDetails.isEmpty()) { + //Long mobileNo = Long.parseLong(familyPensionerDetailsResponse.getFamilyPensionerDetails().get(0).getMobile_no()); + + //Long mobileNo = 8220798933l; + //System.out.println("step 1"); + responseMap.put("EmployeeDetailsResult", employeeDetails ); + }else { + responseMap.put("EmployeeDetailsResult", null ); + } + } + } catch (IOException e) { + e.printStackTrace(); + } + + return responseMap; + } + + @Operation( + summary = "Pensioner Details ERP REST API", + description = "REST API to retrieving the Pensioner Details From ERP" + ) + //checking pensioner Details + @GetMapping("/PensionerDetails") + @ResponseBody + public Map getPensionerDetails(HttpServletRequest request, @RequestParam("id") Long id) { + String purpose = "Checking Employee"; + RestTemplate restTemplate = new RestTemplate(); + String url = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?serviceId=getPensionerDetailsList&pensionerId=" + id; + + ResponseEntity responseEntity = restTemplate.getForEntity(url, String.class); + + // Extract the JSON string from the response body + String jsonString = responseEntity.getBody(); + + // Extract the Java object from the response body + ObjectMapper objectMapper = new ObjectMapper(); + Map responseMap = new HashMap<>(); + + try { + PensionerDetailsResponse pensionerDetailsResponse = objectMapper.readValue(jsonString, PensionerDetailsResponse.class); + + if (pensionerDetailsResponse != null) { + List pensionerDetails = pensionerDetailsResponse.getEmployees(); + + if (pensionerDetails != null && !pensionerDetails.isEmpty()) { + Long mobileNo = Long.parseLong(pensionerDetailsResponse.getEmployees().get(0).getMobile_no()); // Long mobileNo = 9874561230l; - // System.out.println("step 2"); - responseMap.put("mobileNo", mobileNo); - return responseMap; - } else { - responseMap.put("error", "No pensioner details found for the given ID"); - return responseMap; - } - } - - } catch (Exception e) { - e.printStackTrace(); - responseMap.put("error", "An error occurred while processing the request"); - } - - return responseMap; - } - - @Operation( - summary = "Saving Counter Details ERP REST API", - description = "REST API to save the Counter Details" - ) - //Saving the Counter Details - @PostMapping(path = "/counter-booking", consumes = {"multipart/form-data"}) - public ResponseEntity saveCounterBookingDetails(HttpServletRequest request) { - MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; - Map bookingDetails = splitFormData(multipartRequest); - Map saveCounterBooking = counterService.saveCounterBooking(bookingDetails); - return ResponseEntity.ok(saveCounterBooking); - } - - @GetMapping("/checkAvail") - public List checkAvail(@RequestParam("fromDate") String fromDate, - @RequestParam("toDate") String toDate, - @RequestParam("starting") String starting, - @RequestParam("ending") String ending, - @RequestParam(name = "hallId", required = false) String hallId) { - List data = new ArrayList<>(); - HashSet removeHallId = new HashSet(); - int hallIdd = 0; - if (hallId != null && !hallId.equals("")) { - hallIdd = Integer.parseInt(hallId); - } - if (!fromDate.equals(toDate) && (starting.equals(ending) || starting.equals("evening") && ending.equals("morning"))) { - Map mp = incrementAndDecrementAndDaysCount(fromDate, toDate); - long noOfDays = Long.parseLong(mp.get("NoOfDays").toString()); - if (noOfDays > 2) { - data = calendarService.getCalendarByDateAndHallIdAndSlot(mp.get("fromDate"), mp.get("toDate"), starting, ending, hallIdd); - for (int i = 0; i < data.size(); i++) { - removeHallId.add(data.get(i).getHallId()); - } - } - } - - data = calendarService.getCalendarByDateAndHallIdAndSlot(fromDate, toDate, starting, ending, hallIdd); - //System.out.println("data size :-"+data.size()); - - if (starting != null && ending != null) { - boolean checkAvail = false; - int checkHallId = 0; - for (int i = 0; i < data.size(); i++) { - - if ((starting.equals("evening") || ending.equals("morning")) && fromDate.equals(data.get(i).getBdate().toString()) && toDate.equals(fromDate)) { - if (data.get(i).isEveningSlot() == false) { - continue; - } else if (data.get(i).isMorningSlot() == false) { - continue; - } - } else if ((starting.equals(ending) || starting.equals("evening") && ending.equals("morning")) && !toDate.equals(fromDate)) { - if (checkHallId == 0 || checkHallId != data.get(i).getHallId()) { - checkHallId = data.get(i).getHallId(); - checkAvail = false; - } - - if (starting.equals("morning") && ending.equals("morning")) { - if (fromDate.equals(data.get(i).getBdate().toString()) && data.get(i).isMorningSlot() == false) { - if (checkHallId == data.get(i).getHallId()) { - - continue; - } - } else if (toDate.equals(data.get(i).getBdate().toString()) && data.get(i).isMorningSlot() == false) { - if (checkHallId == data.get(i).getHallId() && checkAvail == false) { - checkHallId = data.get(i).getHallId(); - continue; - } - } - } else if (starting.equals("evening") && ending.equals("morning")) { - - if (fromDate.equals(data.get(i).getBdate().toString()) && data.get(i).isEveningSlot() == false) { - if (checkHallId == data.get(i).getHallId()) { - continue; - } - } else if (toDate.equals(data.get(i).getBdate().toString()) && data.get(i).isMorningSlot() == false) { - if (checkHallId == data.get(i).getHallId() && checkAvail == false) { - checkHallId = data.get(i).getHallId(); - continue; - } - } - } else if (starting.equals("evening") && ending.equals("evening")) { - if (fromDate.equals(data.get(i).getBdate().toString()) && data.get(i).isEveningSlot() == false) { - if (checkHallId == data.get(i).getHallId()) { - continue; - } - } else if (toDate.equals(data.get(i).getBdate().toString()) && data.get(i).isEveningSlot() == false) { - if (checkHallId == data.get(i).getHallId() && checkAvail == false) { - checkHallId = data.get(i).getHallId(); - continue; - } - } - } else { - if (checkHallId == data.get(i).getHallId()) { - checkAvail = true; - } - } - } - //System.out.println(data.get(i).getHallId()); - removeHallId.add(data.get(i).getHallId()); - } - } - List removeHallByid = new ArrayList<>(); - if (hallIdd != 0) { - if (hallIdd != data.get(0).getHallId()) { - HallDetails hallDetails = hallDetailService.getHallById(hallIdd); - removeHallByid.add(hallDetails); - } - - } else { - removeHallByid = hallDetailService.removeHallById(removeHallId); - } - return removeHallByid; - } - - Map incrementAndDecrementAndDaysCount(String fromdate, String todate) { - Map mp = new HashMap<>(); - LocalDate increasement = LocalDate.parse(fromdate); - LocalDate decrement = LocalDate.parse(todate); - - LocalDate outputDateFrom = increasement; - LocalDate outputDateToday = decrement; - - long daysDifference = increasement.until(decrement).getDays(); - daysDifference = Math.abs(daysDifference); - - if (fromdate != todate) { - outputDateFrom = increasement.plusDays(1); - outputDateToday = decrement.minusDays(1); - } - - mp.put("fromDate", outputDateFrom.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))); - mp.put("toDate", outputDateToday.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))); - mp.put("NoOfDays", daysDifference + ""); - return mp; - } - - @GetMapping("/getuserDetailsbymobileno") - public Users getuserDetailsbymobileno(@RequestParam long mobileNo) { - return userservice.getUserDetailsByMobileNo(mobileNo); - - } - - //Reschedule - @PostMapping("/reschedule-dates") - public ResponseEntity updateBookingDates( - @RequestParam int bookingId, - @RequestParam String startDate, - @RequestParam String endDate) { - try { - Optional updateResult = bookingService.updateBookingDatesAndCalendar(bookingId, startDate, endDate); - if (updateResult.isPresent()) { - if (updateResult.get().equals("Booking dates updated successfully.")) { - return new ResponseEntity<>(updateResult.get(), HttpStatus.OK); - } else { - // Any other message is treated as an error - return new ResponseEntity<>(updateResult.get(), HttpStatus.BAD_REQUEST); - } - } else { - return new ResponseEntity<>("Booking not found", HttpStatus.NOT_FOUND); - } - } catch (SlotOccupiedException e) { - // Return a bad request status with the exception message - return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST); - } - } - - @GetMapping("/trackBooking") - public List> getTrackingDetails(@RequestParam int bookingId) { - Optional booking = bookingDetailsRepository.findById(bookingId); - List> trackingDetails = new ArrayList<>(); - DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); - DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"); - - if (booking.isPresent()) { - BookingDetails bookingDetails = booking.get(); - - // Payment Success - if (bookingDetails.getPayments() != null) { - Map paymentDetail = new HashMap<>(); - paymentDetail.put("status", "PAYMENT_SUCCESS"); - paymentDetail.put("description", "Payment Success"); - paymentDetail.put("dateTime", bookingDetails.getPayments().getCdate()); // Assuming Cdate is the created date - trackingDetails.add(paymentDetail); - } - - // Booking Approved - if (bookingDetails.getBookingStatus() == BookingStatus.APPROVED) { - Map bookingApprovedDetail = new HashMap<>(); - bookingApprovedDetail.put("status", "APPROVED"); - bookingApprovedDetail.put("description", "Booking Approved"); - bookingApprovedDetail.put("dateTime", bookingDetails.getBookingDate()); // Assuming BookingDate is correct - trackingDetails.add(bookingApprovedDetail); - } - - // Event Completed - LocalDateTime endDate = null; - try { - // Try parsing as LocalDateTime first - try { - endDate = LocalDateTime.parse(bookingDetails.getEndDate(), dateTimeFormatter); - } catch (Exception e) { - // If parsing fails, try parsing as LocalDate - LocalDate endDateOnly = LocalDate.parse(bookingDetails.getEndDate(), dateFormatter); - endDate = endDateOnly.atStartOfDay(); // Convert LocalDate to LocalDateTime at start of the day - } - } catch (Exception e) { - // Handle parsing exception - e.printStackTrace(); - } - - if (endDate != null && bookingDetails.getBookingStatus() == BookingStatus.APPROVED && - endDate.isBefore(LocalDateTime.now().plusDays(1))) { // Compare endDate with current date - Map eventCompletedDetail = new HashMap<>(); - eventCompletedDetail.put("status", "EVENT_COMPLETED"); - eventCompletedDetail.put("description", "Event Completed"); - eventCompletedDetail.put("dateTime", bookingDetails.getEndDate()); - trackingDetails.add(eventCompletedDetail); - } - - // Settlement Raising - if (bookingDetails.getSettlement() != null && bookingDetails.getRefundStatus() == RefundStatus.WAITING) { - Map settlementRaisingDetail = new HashMap<>(); - settlementRaisingDetail.put("status", "SETTLEMENT_RAISING"); - settlementRaisingDetail.put("description", "Settlement Raising"); - settlementRaisingDetail.put("dateTime", bookingDetails.getSettlement().getUpdatedDate()); - trackingDetails.add(settlementRaisingDetail); - } - - // Refund Completed - if (bookingDetails.getBookingStatus() == BookingStatus.COMPLETED - && bookingDetails.getRefundStatus() == BookingDetails.RefundStatus.COMPLETED) { - Map refundCompletedDetail = new HashMap<>(); - refundCompletedDetail.put("status", "COMPLETED"); - refundCompletedDetail.put("description", "Refund Completed"); - refundCompletedDetail.put("dateTime", bookingDetails.getUpdatedDate()); - trackingDetails.add(refundCompletedDetail); - } - - - if (bookingDetails.getBookingStatus() == BookingStatus.CANCELED) { - Map bookingCanceledDetail = new HashMap<>(); - bookingCanceledDetail.put("status", "CANCELED"); - bookingCanceledDetail.put("description", "Booking Cancelled"); - bookingCanceledDetail.put("dateTime", bookingDetails.getUpdatedDate()); // Assuming BookingDate is correct - trackingDetails.add(bookingCanceledDetail); - } - - - if (bookingDetails.getBookingStatus() == BookingStatus.CANCELED - && bookingDetails.getRefundStatus() == RefundStatus.WAITING) { - Map canceledRaisingDetail = new HashMap<>(); - canceledRaisingDetail.put("status", "SETTLEMENT_RAISING"); - canceledRaisingDetail.put("description", "Settlement Raising"); - canceledRaisingDetail.put("dateTime", bookingDetails.getUpdatedDate()); // Assuming BookingDate is correct - trackingDetails.add(canceledRaisingDetail); - } - - if (bookingDetails.getBookingStatus() == BookingStatus.CANCELED - && bookingDetails.getRefundStatus() == BookingDetails.RefundStatus.COMPLETED) { - Map cancelRefundCompletedDetail = new HashMap<>(); - cancelRefundCompletedDetail.put("status", "COMPLETED"); - cancelRefundCompletedDetail.put("description", "Refund Completed"); - cancelRefundCompletedDetail.put("dateTime", bookingDetails.getUpdatedDate()); - trackingDetails.add(cancelRefundCompletedDetail); - } - - if (bookingDetails.getBookingStatus() == BookingStatus.REJECTED) { - Map bookingRejectedDetail = new HashMap<>(); - bookingRejectedDetail.put("status", "REJECTED"); - bookingRejectedDetail.put("description", "Booking Rejected"); - bookingRejectedDetail.put("dateTime", bookingDetails.getUpdatedDate()); // Assuming BookingDate is correct - trackingDetails.add(bookingRejectedDetail); - } - - - if (bookingDetails.getBookingStatus() == BookingStatus.REJECTED - && bookingDetails.getRefundStatus() == RefundStatus.WAITING) { - Map rejectedRaisingDetail = new HashMap<>(); - rejectedRaisingDetail.put("status", "SETTLEMENT_RAISING"); - rejectedRaisingDetail.put("description", "Settlement Raising"); - rejectedRaisingDetail.put("dateTime", bookingDetails.getUpdatedDate()); // Assuming BookingDate is correct - trackingDetails.add(rejectedRaisingDetail); - } - - if (bookingDetails.getBookingStatus() == BookingStatus.REJECTED - && bookingDetails.getRefundStatus() == BookingDetails.RefundStatus.COMPLETED) { - Map rejectedRefundCompletedDetail = new HashMap<>(); - rejectedRefundCompletedDetail.put("status", "COMPLETED"); - rejectedRefundCompletedDetail.put("description", "Refund Completed"); - rejectedRefundCompletedDetail.put("dateTime", bookingDetails.getUpdatedDate()); - trackingDetails.add(rejectedRefundCompletedDetail); - } - - - if (bookingDetails.getBookingStatus() == BookingStatus.GCC_BLOCKED) { - Map gccBlockedDetail = new HashMap<>(); - gccBlockedDetail.put("status", "GCC_BLOCKED"); - gccBlockedDetail.put("description", "GCC Blocked"); - gccBlockedDetail.put("dateTime", bookingDetails.getUpdatedDate()); - trackingDetails.add(gccBlockedDetail); - } - } - return trackingDetails; - } - - - @GetMapping("/confirmstatebooking") - public String Confirmstatebookig(@RequestParam int bookingId) { - String response = bookingService.confirmStateBooking(bookingId); - return response; - } - - @PostMapping("/uploaddocs") - public ResponseEntity uploadDocs(@RequestParam("nocFile") MultipartFile file, - @RequestParam("bookingssId") int bookingId) { - try { - bookingService.uploadNOCFile(file, bookingId); - return ResponseEntity.ok("File uploaded and saved successfully"); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("File upload failed: " + e.getMessage()); - } - } - + // System.out.println("step 2"); + responseMap.put("mobileNo", mobileNo); + return responseMap; + } else { + responseMap.put("error", "No pensioner details found for the given ID"); + return responseMap; + } + } + + } catch (Exception e) { + e.printStackTrace(); + responseMap.put("error", "An error occurred while processing the request"); + } + + return responseMap; + } + + @Operation( + summary = "Saving Counter Details ERP REST API", + description = "REST API to save the Counter Details" + ) + //Saving the Counter Details + @PostMapping(path = "/counter-booking", consumes = { "multipart/form-data" }) + public ResponseEntity saveCounterBookingDetails(HttpServletRequest request) { + MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; + Map bookingDetails = splitFormData(multipartRequest); + Map saveCounterBooking = counterService.saveCounterBooking(bookingDetails); + return ResponseEntity.ok(saveCounterBooking); + } + @GetMapping("/checkAvail") + public List checkAvail(@RequestParam("fromDate") String fromDate, + @RequestParam("toDate") String toDate, + @RequestParam("starting") String starting, + @RequestParam("ending") String ending, + @RequestParam(name = "hallId",required = false) String hallId){ + List data = new ArrayList<>(); + HashSet removeHallId = new HashSet(); + int hallIdd=0; + if(hallId != null && !hallId.equals("")){ + hallIdd = Integer.parseInt(hallId); + } + if(!fromDate.equals(toDate) && (starting.equals(ending) || starting.equals("evening") && ending.equals("morning"))){ + Map mp =incrementAndDecrementAndDaysCount(fromDate,toDate); + long noOfDays= Long.parseLong(mp.get("NoOfDays").toString()); + if(noOfDays>2){ + data = calendarService.getCalendarByDateAndHallIdAndSlot(mp.get("fromDate"),mp.get("toDate"),starting,ending,hallIdd); + for(int i=0;i removeHallByid = new ArrayList<>(); + if(hallIdd!=0){ + if(hallIdd!=data.get(0).getHallId()){ + HallDetails hallDetails = hallDetailService.getHallById(hallIdd); + removeHallByid.add(hallDetails); + } + + }else { + removeHallByid = hallDetailService.removeHallById(removeHallId); + } + return removeHallByid; + } + + Map incrementAndDecrementAndDaysCount(String fromdate, String todate){ + Map mp = new HashMap<>(); + LocalDate increasement = LocalDate.parse(fromdate); + LocalDate decrement = LocalDate.parse(todate); + + LocalDate outputDateFrom =increasement; + LocalDate outputDateToday = decrement; + + long daysDifference = increasement.until(decrement).getDays(); + daysDifference = Math.abs(daysDifference); + + if(fromdate!=todate) { + outputDateFrom = increasement.plusDays(1); + outputDateToday = decrement.minusDays(1); + } + + mp.put("fromDate", outputDateFrom.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))); + mp.put("toDate",outputDateToday.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))); + mp.put("NoOfDays",daysDifference+""); + return mp; + } + + @GetMapping("/getuserDetailsbymobileno") + public Users getuserDetailsbymobileno(@RequestParam long mobileNo) { + return userservice.getUserDetailsByMobileNo(mobileNo); + + } + + //Reschedule + @PostMapping("/reschedule-dates") + public ResponseEntity updateBookingDates( + @RequestParam int bookingId, + @RequestParam String startDate, + @RequestParam String endDate) { + try { + Optional updateResult = bookingService.updateBookingDatesAndCalendar(bookingId, startDate, endDate); + if (updateResult.isPresent()) { + if (updateResult.get().equals("Booking dates updated successfully.")) { + return new ResponseEntity<>(updateResult.get(), HttpStatus.OK); + } else { + // Any other message is treated as an error + return new ResponseEntity<>(updateResult.get(), HttpStatus.BAD_REQUEST); + } + } else { + return new ResponseEntity<>("Booking not found", HttpStatus.NOT_FOUND); + } + } catch (SlotOccupiedException e) { + // Return a bad request status with the exception message + return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST); + } + } + + @GetMapping("/trackBooking") + public List> getTrackingDetails(@RequestParam int bookingId) { + Optional booking = bookingDetailsRepository.findById(bookingId); + List> trackingDetails = new ArrayList<>(); + DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"); + + if (booking.isPresent()) { + BookingDetails bookingDetails = booking.get(); + + // Payment Success + if (bookingDetails.getPayments() != null) { + Map paymentDetail = new HashMap<>(); + paymentDetail.put("status", "PAYMENT_SUCCESS"); + paymentDetail.put("description", "Payment Success"); + paymentDetail.put("dateTime", bookingDetails.getPayments().getCdate()); // Assuming Cdate is the created date + trackingDetails.add(paymentDetail); + } + + // Booking Approved + if (bookingDetails.getBookingStatus() == BookingStatus.APPROVED) { + Map bookingApprovedDetail = new HashMap<>(); + bookingApprovedDetail.put("status", "APPROVED"); + bookingApprovedDetail.put("description", "Booking Approved"); + bookingApprovedDetail.put("dateTime", bookingDetails.getBookingDate()); // Assuming BookingDate is correct + trackingDetails.add(bookingApprovedDetail); + } + + // Event Completed + LocalDateTime endDate = null; + try { + // Try parsing as LocalDateTime first + try { + endDate = LocalDateTime.parse(bookingDetails.getEndDate(), dateTimeFormatter); + } catch (Exception e) { + // If parsing fails, try parsing as LocalDate + LocalDate endDateOnly = LocalDate.parse(bookingDetails.getEndDate(), dateFormatter); + endDate = endDateOnly.atStartOfDay(); // Convert LocalDate to LocalDateTime at start of the day + } + } catch (Exception e) { + // Handle parsing exception + e.printStackTrace(); + } + + if (endDate != null && bookingDetails.getBookingStatus() == BookingStatus.APPROVED && + endDate.isBefore(LocalDateTime.now().plusDays(1))) { // Compare endDate with current date + Map eventCompletedDetail = new HashMap<>(); + eventCompletedDetail.put("status", "EVENT_COMPLETED"); + eventCompletedDetail.put("description", "Event Completed"); + eventCompletedDetail.put("dateTime", bookingDetails.getEndDate()); + trackingDetails.add(eventCompletedDetail); + } + + // Settlement Raising + if (bookingDetails.getSettlement() != null && bookingDetails.getRefundStatus() == RefundStatus.WAITING) { + Map settlementRaisingDetail = new HashMap<>(); + settlementRaisingDetail.put("status", "SETTLEMENT_RAISING"); + settlementRaisingDetail.put("description", "Settlement Raising"); + settlementRaisingDetail.put("dateTime", bookingDetails.getSettlement().getUpdatedDate() ); + trackingDetails.add(settlementRaisingDetail); + } + + // Refund Completed + if (bookingDetails.getBookingStatus() == BookingStatus.COMPLETED + && bookingDetails.getRefundStatus() == BookingDetails.RefundStatus.COMPLETED) { + Map refundCompletedDetail = new HashMap<>(); + refundCompletedDetail.put("status", "COMPLETED"); + refundCompletedDetail.put("description", "Refund Completed"); + refundCompletedDetail.put("dateTime", bookingDetails.getUpdatedDate()); + trackingDetails.add(refundCompletedDetail); + } + + + if (bookingDetails.getBookingStatus() == BookingStatus.CANCELED){ + Map bookingCanceledDetail = new HashMap<>(); + bookingCanceledDetail.put("status","CANCELED"); + bookingCanceledDetail.put("description", "Booking Cancelled"); + bookingCanceledDetail.put("dateTime", bookingDetails.getUpdatedDate()); // Assuming BookingDate is correct + trackingDetails.add(bookingCanceledDetail); + } + + + if (bookingDetails.getBookingStatus() == BookingStatus.CANCELED + && bookingDetails.getRefundStatus() == RefundStatus.WAITING){ + Map canceledRaisingDetail = new HashMap<>(); + canceledRaisingDetail.put("status","SETTLEMENT_RAISING"); + canceledRaisingDetail.put("description", "Settlement Raising"); + canceledRaisingDetail.put("dateTime", bookingDetails.getUpdatedDate()); // Assuming BookingDate is correct + trackingDetails.add(canceledRaisingDetail); + } + + if (bookingDetails.getBookingStatus() == BookingStatus.CANCELED + && bookingDetails.getRefundStatus() == BookingDetails.RefundStatus.COMPLETED){ + Map cancelRefundCompletedDetail = new HashMap<>(); + cancelRefundCompletedDetail.put("status", "COMPLETED"); + cancelRefundCompletedDetail.put("description", "Refund Completed"); + cancelRefundCompletedDetail.put("dateTime", bookingDetails.getUpdatedDate()); + trackingDetails.add(cancelRefundCompletedDetail); + } + + if (bookingDetails.getBookingStatus() == BookingStatus.REJECTED){ + Map bookingRejectedDetail = new HashMap<>(); + bookingRejectedDetail.put("status","REJECTED"); + bookingRejectedDetail.put("description", "Booking Rejected"); + bookingRejectedDetail.put("dateTime", bookingDetails.getUpdatedDate()); // Assuming BookingDate is correct + trackingDetails.add(bookingRejectedDetail); + } + + + if (bookingDetails.getBookingStatus() == BookingStatus.REJECTED + && bookingDetails.getRefundStatus() == RefundStatus.WAITING){ + Map rejectedRaisingDetail = new HashMap<>(); + rejectedRaisingDetail.put("status","SETTLEMENT_RAISING"); + rejectedRaisingDetail.put("description", "Settlement Raising"); + rejectedRaisingDetail.put("dateTime", bookingDetails.getUpdatedDate()); // Assuming BookingDate is correct + trackingDetails.add(rejectedRaisingDetail); + } + + if (bookingDetails.getBookingStatus() == BookingStatus.REJECTED + && bookingDetails.getRefundStatus() == BookingDetails.RefundStatus.COMPLETED){ + Map rejectedRefundCompletedDetail = new HashMap<>(); + rejectedRefundCompletedDetail.put("status", "COMPLETED"); + rejectedRefundCompletedDetail.put("description", "Refund Completed"); + rejectedRefundCompletedDetail.put("dateTime", bookingDetails.getUpdatedDate()); + trackingDetails.add(rejectedRefundCompletedDetail); + } + + + + if (bookingDetails.getBookingStatus() == BookingStatus.GCC_BLOCKED){ + Map gccBlockedDetail = new HashMap<>(); + gccBlockedDetail.put("status","GCC_BLOCKED"); + gccBlockedDetail.put("description", "GCC Blocked"); + gccBlockedDetail.put("dateTime", bookingDetails.getUpdatedDate()); + trackingDetails.add(gccBlockedDetail); + } + } + return trackingDetails; + } + + + @GetMapping("/confirmstatebooking") + public String Confirmstatebookig(@RequestParam int bookingId ) { + String response=bookingService.confirmStateBooking(bookingId); + return response; + } + + @PostMapping("/uploaddocs") + public ResponseEntity uploadDocs(@RequestParam("nocFile") MultipartFile file, + @RequestParam("bookingssId") int bookingId) { + try { + bookingService.uploadNOCFile(file, bookingId); + return ResponseEntity.ok("File uploaded and saved successfully"); + } catch (Exception e) { + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("File upload failed: " + e.getMessage()); + } + } + /*@GetMapping("/calculatehallamount") + public ResponseEntity> getHallDetailsConcession( + @RequestParam int numDays, + @RequestParam(value = "startPeriod", required = false) String startPeriod, + @RequestParam(value = "endPeriod", required = false) String endPeriod, + @RequestParam(value = "reasonforBooking", required = false) String reasonforBooking, + @RequestParam int hallId) { + + Optional hallDetailsOpt = hallDetailsRepository.findById(hallId); + + if (!hallDetailsOpt.isPresent()) { + return ResponseEntity.status(404).body(null); // Handle not found + } + + HallDetails hallDetails = hallDetailsOpt.get(); + boolean isSGE = hallDetails.isSGE(); + boolean isCGE = hallDetails.isCGE(); + + double fullDayAmount = hallDetails.getFullDayRent(); + double halfDayAmount = hallDetails.getHalfDayRent(); + double depositAmount = hallDetails.getDepositAmount(); + double gstRate = hallDetails.getGst(); + + Map response = new HashMap<>(); + + double amount = calculateAmount(numDays, startPeriod, endPeriod, fullDayAmount, halfDayAmount); + double totalDepositAmount = depositAmount * numDays; + double totalAmount; + double discountAmount = 0.0; + response.put("reasonforBooking", reasonforBooking); + + if (!isSGE) { + totalAmount = amount + (amount * gstRate / 100) + totalDepositAmount; + response.put("discount", 0); + response.put("amount", amount); + response.put("totalAmount", totalAmount); + response.put("depositAmount", totalDepositAmount); + double gstValue =gstRate * amount / 100.0; + response.put("gst", gstValue); + response.put("discountAmount", amount); + } else { + if ("SGE".equals(reasonforBooking)) { + double cleaningCharges = hallDetails.getHallDetailsConcession().get(0).getFullDayCleaningcharges(); + double pasystem=hallDetails.getHallDetailsConcession().get(0).getFulldayPAsystem(); + double ebCharges=hallDetails.getHallDetailsConcession().get(0).getFulldayEBcharges(); + double halfcleaningCharges = hallDetails.getHallDetailsConcession().get(0).getHalfDayCleaningcharges(); + double halfpasystem=hallDetails.getHallDetailsConcession().get(0).getHalfdayPAsystem(); + double halfebCharges=hallDetails.getHallDetailsConcession().get(0).getHalfdayEBcharges(); + double fulladditionalCharges = cleaningCharges+pasystem+ebCharges; + double halfadditionalCharges = halfcleaningCharges+halfpasystem+halfebCharges; + double fulldayhallAmount=hallDetails.getHallDetailsConcession().get(0).getFulldayhallamount(); + double halfdayhallAmount=hallDetails.getHallDetailsConcession().get(0).getHalfdayhallamount(); + double additionalCharges=calculateAmount(numDays, startPeriod, endPeriod, fulladditionalCharges, halfadditionalCharges); + totalAmount = additionalCharges + totalDepositAmount + (additionalCharges * gstRate / 100.0); + discountAmount = (fulldayhallAmount * hallDetails.getSGEdiscount()) / 100.0; + response.put("startperiod", startPeriod); + response.put("endPeriod", endPeriod); + response.put("fulldayhallAmount", fulldayhallAmount); + response.put("halfdayhallAmount", halfdayhallAmount); + response.put("discount", hallDetails.getSGEdiscount()); + response.put("rentAmount", 0); + response.put("additionalCharges", additionalCharges); + response.put("netAmount", additionalCharges); + response.put("gst", gstRate * additionalCharges / 100); + response.put("depositAmount", totalDepositAmount); + response.put("totalAmount", totalAmount); + response.put("discountAmount", discountAmount); + } else if ("CGE".equals(reasonforBooking)) { + response.put("discount", hallDetails.getCGEdiscount()); + discountAmount = (amount * hallDetails.getCGEdiscount()) / 100.0; + totalAmount = discountAmount + totalDepositAmount + (discountAmount * gstRate / 100); + response.put("amount", amount); + response.put("totalAmount", totalAmount); + response.put("depositAmount", totalDepositAmount); + double gstValue = gstRate * discountAmount / 100; + response.put("gst", gstValue); + response.put("discountAmount", discountAmount); + } else { + totalAmount = amount + (amount * gstRate / 100) + totalDepositAmount; + response.put("discount", 0); + response.put("amount", amount); + response.put("totalAmount", totalAmount); + response.put("depositAmount", totalDepositAmount); + double gstValue =gstRate * amount / 100.0; + response.put("gst", gstValue); + response.put("discountAmount", amount); + } + } + + return ResponseEntity.ok(response); + } + public double calculateAmount(double numDays, String startPeriod, String endPeriod, double fullDayAmount, double halfDayAmount) { + double amount = 0; + + // If there is only one day + if (numDays == 1) { + if ("1".equals(startPeriod) && "2".equals(endPeriod)) { + amount = fullDayAmount; + } else if ("1".equals(startPeriod) && "1".equals(endPeriod)) { + amount = halfDayAmount; + } else if ("2".equals(startPeriod) && "2".equals(endPeriod)) { + amount = halfDayAmount; + }else { + amount=numDays; + } + } else { + // For multiple days + if ("1".equals(startPeriod) && "2".equals(endPeriod)) { + amount = fullDayAmount * numDays; + } else if ("1".equals(startPeriod) && "1".equals(endPeriod)) { + amount = fullDayAmount * (numDays - 1) + halfDayAmount; + } else if ("2".equals(startPeriod) && "2".equals(endPeriod)) { + amount = fullDayAmount * (numDays - 1) + halfDayAmount; + } else if ("2".equals(startPeriod) && "1".equals(endPeriod)) { + amount = fullDayAmount * (numDays - 2) + halfDayAmount * 2; + }else { + amount=numDays; + } + } + + return amount; + }*/ @GetMapping("/calculatehallamount") public ResponseEntity> getHallDetailsConcession( @@ -1622,7 +1723,7 @@ public class UserAPIController { Map response = new HashMap<>(); double amount = calculateAmount(numDays, startPeriod, endPeriod, fullDayAmount, halfDayAmount); - double totalDepositAmount = depositAmount * numDays; + double totalDepositAmount = calculateDepositAmount(numDays, startPeriod, endPeriod, depositAmount); double totalAmount; double discountAmount = 0.0; response.put("reasonforBooking", reasonforBooking); @@ -1633,22 +1734,22 @@ public class UserAPIController { response.put("amount", amount); response.put("totalAmount", totalAmount); response.put("depositAmount", totalDepositAmount); - double gstValue = gstRate * amount / 100.0; + double gstValue =gstRate * amount / 100.0; response.put("gst", gstValue); response.put("discountAmount", amount); } else { if ("SGE".equals(reasonforBooking)) { double cleaningCharges = hallDetails.getHallDetailsConcession().get(0).getFullDayCleaningcharges(); - double pasystem = hallDetails.getHallDetailsConcession().get(0).getFulldayPAsystem(); - double ebCharges = hallDetails.getHallDetailsConcession().get(0).getFulldayEBcharges(); + double pasystem=hallDetails.getHallDetailsConcession().get(0).getFulldayPAsystem(); + double ebCharges=hallDetails.getHallDetailsConcession().get(0).getFulldayEBcharges(); double halfcleaningCharges = hallDetails.getHallDetailsConcession().get(0).getHalfDayCleaningcharges(); - double halfpasystem = hallDetails.getHallDetailsConcession().get(0).getHalfdayPAsystem(); - double halfebCharges = hallDetails.getHallDetailsConcession().get(0).getHalfdayEBcharges(); - double fulladditionalCharges = cleaningCharges + pasystem + ebCharges; - double halfadditionalCharges = halfcleaningCharges + halfpasystem + halfebCharges; - double fulldayhallAmount = hallDetails.getHallDetailsConcession().get(0).getFulldayhallamount(); - double halfdayhallAmount = hallDetails.getHallDetailsConcession().get(0).getHalfdayhallamount(); - double additionalCharges = calculateAmount(numDays, startPeriod, endPeriod, fulladditionalCharges, halfadditionalCharges); + double halfpasystem=hallDetails.getHallDetailsConcession().get(0).getHalfdayPAsystem(); + double halfebCharges=hallDetails.getHallDetailsConcession().get(0).getHalfdayEBcharges(); + double fulladditionalCharges = cleaningCharges+pasystem+ebCharges; + double halfadditionalCharges = halfcleaningCharges+halfpasystem+halfebCharges; + double fulldayhallAmount=hallDetails.getHallDetailsConcession().get(0).getFulldayhallamount(); + double halfdayhallAmount=hallDetails.getHallDetailsConcession().get(0).getHalfdayhallamount(); + double additionalCharges=calculateAmount(numDays, startPeriod, endPeriod, fulladditionalCharges, halfadditionalCharges); totalAmount = additionalCharges + totalDepositAmount + (additionalCharges * gstRate / 100.0); discountAmount = (fulldayhallAmount * hallDetails.getSGEdiscount()) / 100.0; response.put("startperiod", startPeriod); @@ -1664,29 +1765,19 @@ public class UserAPIController { response.put("totalAmount", totalAmount); response.put("discountAmount", discountAmount); } else if ("CGE".equals(reasonforBooking)) { - /*response.put("discount", hallDetails.getCGEdiscount()); - discountAmount = (amount * hallDetails.getCGEdiscount()) / 100.0; - totalAmount = discountAmount + totalDepositAmount + (discountAmount * gstRate / 100); - response.put("amount", amount); - response.put("totalAmount", totalAmount); - response.put("depositAmount", totalDepositAmount); - double gstValue = gstRate * discountAmount / 100; - response.put("gst", gstValue); - response.put("discountAmount", discountAmount);*/ - double cleaningCharges = hallDetails.getHallDetailsConcession().get(0).getFullDayCleaningcharges(); - double pasystem = hallDetails.getHallDetailsConcession().get(0).getFulldayPAsystem(); - double ebCharges = hallDetails.getHallDetailsConcession().get(0).getFulldayEBcharges(); + double pasystem=hallDetails.getHallDetailsConcession().get(0).getFulldayPAsystem(); + double ebCharges=hallDetails.getHallDetailsConcession().get(0).getFulldayEBcharges(); double halfcleaningCharges = hallDetails.getHallDetailsConcession().get(0).getHalfDayCleaningcharges(); - double halfpasystem = hallDetails.getHallDetailsConcession().get(0).getHalfdayPAsystem(); - double halfebCharges = hallDetails.getHallDetailsConcession().get(0).getHalfdayEBcharges(); - double fulladditionalCharges = cleaningCharges + pasystem + ebCharges; - double halfadditionalCharges = halfcleaningCharges + halfpasystem + halfebCharges; - double additionalCharges = calculateAmount(numDays, startPeriod, endPeriod, fulladditionalCharges, halfadditionalCharges); + double halfpasystem=hallDetails.getHallDetailsConcession().get(0).getHalfdayPAsystem(); + double halfebCharges=hallDetails.getHallDetailsConcession().get(0).getHalfdayEBcharges(); + double fulladditionalCharges = cleaningCharges+pasystem+ebCharges; + double halfadditionalCharges = halfcleaningCharges+halfpasystem+halfebCharges; + double additionalCharges=calculateAmount(numDays, startPeriod, endPeriod, fulladditionalCharges, halfadditionalCharges); double rentAmount = (amount * hallDetails.getCGEdiscount()) / 100.0; double netAmount = rentAmount + additionalCharges; - double gst = ((additionalCharges + rentAmount) * gstRate / 100.0); - totalAmount = Math.floor((netAmount + gst + totalDepositAmount) * 100) / 100.0; + double gst = ((additionalCharges+rentAmount) * gstRate / 100.0); + totalAmount = Math.floor((netAmount + gst + totalDepositAmount) * 100) / 100.0 ; response.put("startperiod", startPeriod); response.put("endPeriod", endPeriod); response.put("fulldayhallAmount", fullDayAmount); @@ -1700,12 +1791,12 @@ public class UserAPIController { response.put("totalAmount", totalAmount); response.put("discountAmount", discountAmount); } else { - totalAmount = amount + (amount * gstRate / 100) + totalDepositAmount; + double gstValue =(gstRate * amount) / 100.0; + totalAmount = Math.ceil((amount + gstValue + totalDepositAmount) * 100) / 100; response.put("discount", 0); response.put("amount", amount); response.put("totalAmount", totalAmount); response.put("depositAmount", totalDepositAmount); - double gstValue = gstRate * amount / 100.0; response.put("gst", gstValue); response.put("discountAmount", amount); } @@ -1713,7 +1804,6 @@ public class UserAPIController { return ResponseEntity.ok(response); } - public double calculateAmount(double numDays, String startPeriod, String endPeriod, double fullDayAmount, double halfDayAmount) { double amount = 0; @@ -1725,8 +1815,8 @@ public class UserAPIController { amount = halfDayAmount; } else if ("2".equals(startPeriod) && "2".equals(endPeriod)) { amount = halfDayAmount; - } else { - amount = numDays; + }else { + amount=numDays; } } else { // For multiple days @@ -1738,39 +1828,86 @@ public class UserAPIController { amount = fullDayAmount * (numDays - 1) + halfDayAmount; } else if ("2".equals(startPeriod) && "1".equals(endPeriod)) { amount = fullDayAmount * (numDays - 2) + halfDayAmount * 2; - } else { - amount = numDays; + }else { + amount=numDays; } } return amount; } - @GetMapping("/getTransactionDetails") - public Map getTransactionDetails(@RequestParam String userId) { - // Fetch all transaction details for the user - List transactions = PaymentGatewayServiceImpl.getTransactionResponseByuserId(userId); + @GetMapping("/getTransactionDetails") + public Map getTransactionDetails(@RequestParam String userId) { + // Fetch all transaction details for the user + List transactions = PaymentGatewayServiceImpl.getTransactionResponseByuserId(userId); + + Map response = new HashMap<>(); + response.put("transactions", transactions); - Map response = new HashMap<>(); - response.put("transactions", transactions); + // Fetch all refund details for the user in a single query + List refundDetails = transRefundResRepository.getRefundResponseByuserId(userId); + + response.put("refundDetails", refundDetails); + + System.out.println("Response: " + response); - // Fetch all refund details for the user in a single query - List refundDetails = transRefundResRepository.getRefundResponseByuserId(userId); + return response; + } - response.put("refundDetails", refundDetails); - System.out.println("Response: " + response); + @GetMapping("/collectionpendingacknowledgementsss") + public BookingDetails viewCollectionpendingAck(Model model,int bookingId){ + BookingDetails bookingsDetails = bookingService.getBookingsById(bookingId); + model.addAttribute("bookingsDetails",bookingsDetails); // Add single BookingDetails object + model.addAttribute("userName",userSession.getDispayName()); + return bookingsDetails; + } - return response; + @GetMapping("/checkQueue") + public ResponseEntity> checkQueue( + @RequestParam String bookingDate, + @RequestParam Long hallId) { + try { + List bookings = bookingService.getBookingsByDateAndHall(bookingDate, hallId); + return ResponseEntity.ok(bookings); + } catch (Exception e) { + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); + } } + public double calculateDepositAmount(double numDays, String startPeriod, String endPeriod, double depositAmount) { + double damount = 0; - @GetMapping("/collectionpendingacknowledgementsss") - public BookingDetails viewCollectionpendingAck(Model model, int bookingId) { - BookingDetails bookingsDetails = bookingService.getBookingsById(bookingId); - model.addAttribute("bookingsDetails", bookingsDetails); // Add single BookingDetails object - model.addAttribute("userName", userSession.getDispayName()); - return bookingsDetails; + // If there is only one day + if (numDays == 1) { + if ("1".equals(startPeriod) && "2".equals(endPeriod)) { + damount = depositAmount; + } else if ("1".equals(startPeriod) && "1".equals(endPeriod)) { + damount = depositAmount; + } else if ("2".equals(startPeriod) && "2".equals(endPeriod)) { + damount = depositAmount; + } else { + damount = numDays; + } + } else { + // For multiple days + if ("1".equals(startPeriod) && "2".equals(endPeriod)) { + damount = depositAmount * numDays; + } else if ("1".equals(startPeriod) && "1".equals(endPeriod)) { + damount = depositAmount * (numDays - 1) + depositAmount; + } else if ("2".equals(startPeriod) && "2".equals(endPeriod)) { + damount = depositAmount * (numDays - 1) + depositAmount; + } else if ("2".equals(startPeriod) && "1".equals(endPeriod)) { + damount = depositAmount * (numDays - 2) + depositAmount; + } else { + damount = numDays; + } + } + + return damount; } + + + } diff --git a/src/main/java/com/gcc/communityHall/controller/UserController.java b/src/main/java/com/gcc/communityHall/controller/UserController.java index 44700235..f69d5947 100644 --- a/src/main/java/com/gcc/communityHall/controller/UserController.java +++ b/src/main/java/com/gcc/communityHall/controller/UserController.java @@ -6,7 +6,6 @@ import java.util.HashSet; import java.util.List; import java.util.Map; -import jakarta.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; @@ -32,285 +31,284 @@ import com.gcc.communityHall.service.UserService; import com.gcc.communityHall.service.Impl.WhatsappMsgServiceImpl; @Controller -@RequestMapping(value={"/communityhall/user","/communityhall","","/"}) +@RequestMapping(value = {"/communityhall/user", "/communityhall", "", "/"}) public class UserController { - @Autowired UserSession userSession; + @Autowired + UserSession userSession; - @Autowired - private BookingService bookingService; - @Autowired - private HallDetailsRepository hallDetailsRepository; - @Autowired - private HallDetailService hallDetailsService; + @Autowired + private BookingService bookingService; + @Autowired + private HallDetailsRepository hallDetailsRepository; + @Autowired + private HallDetailService hallDetailsService; - @Autowired - private UserService userService; + @Autowired + private UserService userService; @Autowired CalendarService calendarService; - + @Autowired private WhatsappMsgServiceImpl whatsappMsgServiceImpl; @Autowired private HallDetailService hallDetailService; - + @Autowired private NotificationRepository notificationRepository; - @GetMapping(value = {"","/","/dashboard","/index"}) + @GetMapping(value = {"", "/", "/dashboard", "/index"}) public String viewDashboard(Model model) { - List halls=hallDetailsRepository.findActiveHalls(); - List hallnames=hallDetailsService.getHallNames(); - for (HallDetails hall : halls) { + List halls = hallDetailsRepository.findActiveHalls(); + List hallnames = hallDetailsService.getHallNames(); + for (HallDetails hall : halls) { if (hall.getHallImagesList() != null && !hall.getHallImagesList().isEmpty()) { model.addAttribute("hasImages", true); break; } } - List newnotification = notificationRepository.findActivenotifications(); + List newnotification = notificationRepository.findActivenotifications(); + + // Create a string to concatenate all notifications descriptions + StringBuilder notificationText = new StringBuilder(); + + for (Notification notification : newnotification) { + notificationText.append(notification.getNotification_description()); + } + + // Pass the concatenated string to the model + model.addAttribute("newnotification", notificationText.toString()); + model.addAttribute("userName", userSession.getDispayName()); + model.addAttribute("halls", halls); + model.addAttribute("hallnames", hallnames); + return "user/dashboard"; + } + + //Checkavilability Api + @GetMapping("/checkAvail") + public String checkAvail(@RequestParam("fromDate") String fromDate, + @RequestParam("toDate") String toDate, + @RequestParam("starting") String starting, + @RequestParam("ending") String ending, + @RequestParam(name = "hallId", required = false) String hallId, + @RequestParam(name = "zone", required = false) String zone, + Model model) { + + List newnotification = notificationRepository.findActivenotifications(); - // Create a string to concatenate all notifications descriptions - StringBuilder notificationText = new StringBuilder(); + // Create a string to concatenate all notifications descriptions + StringBuilder notificationText = new StringBuilder(); + + for (Notification notification : newnotification) { + notificationText.append(notification.getNotification_description()); + } + + // Pass the concatenated string to the model + model.addAttribute("newnotification", notificationText.toString()); + + List hallnames = hallDetailService.getHallNames(); + List hallsByZone; + int hallIdd = 0; + + // Parse hallId if provided + if (hallId != null && !hallId.isEmpty()) { + try { + hallIdd = Integer.parseInt(hallId); + } catch (NumberFormatException e) { + System.err.println("Invalid hallId: " + hallId); + } + } + + // Fetch halls by zone if zone is provided + if (zone != null && !zone.isEmpty()) { + hallsByZone = hallDetailsRepository.findByZone(zone); + } else { + hallsByZone = hallDetailsRepository.findActiveHalls(); + } + + // Fetch calendar data based on provided parameters + List data = calendarService.getCalendarByDateAndHallIdAndSlot(fromDate, toDate, starting, ending, hallIdd); + HashSet removeHallId = new HashSet<>(); + + // Collect hall IDs to be removed + for (BookingCalendar calendar : data) { + boolean isSameDay = fromDate.equals(toDate) && fromDate.equals(calendar.getBdate().toString()); + boolean isMorningStart = starting.equals("1"); + boolean isMorningEnd = ending.equals("1"); + boolean isEveningStart = starting.equals("2"); + boolean isEveningEnd = ending.equals("2"); + + if (isSameDay) { + // Same day booking cases + if (isMorningStart && isMorningEnd && (calendar.getBdate().toString().equals(fromDate) && calendar.isMorningSlot())) { + // System.out.println("Same day morning-morning match found: hallId=" + calendar.getHallId()); + removeHallId.add(calendar.getHallId()); + } else if (isEveningStart && isEveningEnd && (calendar.getBdate().toString().equals(fromDate) && calendar.isEveningSlot())) { + // System.out.println("Same day evening-evening match found: hallId=" + calendar.getHallId()); + removeHallId.add(calendar.getHallId()); + } else if (isMorningStart && isEveningEnd && + ((calendar.getBdate().toString().equals(fromDate) && calendar.isMorningSlot()) || + (calendar.getBdate().toString().equals(toDate) && calendar.isEveningSlot()))) { + // System.out.println("Same day morning-evening match found: hallId=" + calendar.getHallId()); + removeHallId.add(calendar.getHallId()); + } + } else { + // Multi-day booking cases + if ((isMorningStart && isMorningEnd) && + ((calendar.getBdate().toString().equals(fromDate) && calendar.isMorningSlot()) || + (calendar.getBdate().toString().equals(toDate) && calendar.isMorningSlot()))) { + // System.out.println("Multi-day morning-morning match found: hallId=" + calendar.getHallId()); + removeHallId.add(calendar.getHallId()); + } else if ((isEveningStart && isEveningEnd) && + ((calendar.getBdate().toString().equals(fromDate) && calendar.isEveningSlot()) || + (calendar.getBdate().toString().equals(toDate) && calendar.isEveningSlot()))) { + // System.out.println("Multi-day evening-evening match found: hallId=" + calendar.getHallId()); + removeHallId.add(calendar.getHallId()); + } else if (isMorningStart && isEveningEnd && + ((calendar.getBdate().toString().equals(fromDate) && calendar.isMorningSlot()) || + (calendar.getBdate().toString().equals(toDate) && calendar.isEveningSlot()))) { + // System.out.println("Multi-day morning-evening match found: hallId=" + calendar.getHallId()); + removeHallId.add(calendar.getHallId()); + } else if (isEveningStart && isMorningEnd && + ((calendar.getBdate().toString().equals(fromDate) && calendar.isEveningSlot()) || + (calendar.getBdate().toString().equals(toDate) && calendar.isMorningSlot()))) { + //System.out.println("Multi-day evening-morning match found: hallId=" + calendar.getHallId()); + removeHallId.add(calendar.getHallId()); + } + } + } + + // Remove unavailable halls from the list + hallsByZone.removeIf(hall -> removeHallId.contains(hall.getHallId())); + List removeHallById = new ArrayList<>(); + if (hallIdd != 0) { + HallDetails hallDetails = hallDetailService.getHallById(hallIdd); + // Ensure the hall is available before adding it to the list + if (!removeHallId.contains(hallIdd)) { + removeHallById.add(hallDetails); + } + } else { + removeHallById = hallDetailService.removeHallById(removeHallId); + } - for (Notification notification : newnotification) { - notificationText.append(notification.getNotification_description()); - } + // Populate the model attributes + model.addAttribute("userName", userSession.getDispayName()); + model.addAttribute("hallnames", hallnames); + model.addAttribute("fromDate", fromDate); + model.addAttribute("toDate", toDate); + model.addAttribute("startingSlot", starting.equals("1") ? "Morning" : "Evening"); + model.addAttribute("endingSlot", ending.equals("1") ? "Morning" : "Evening"); + model.addAttribute("halls", (hallId != null && !hallId.isEmpty()) ? removeHallById : hallsByZone); - // Pass the concatenated string to the model - model.addAttribute("newnotification", notificationText.toString()); - model.addAttribute("userName",userSession.getDispayName()); - model.addAttribute("halls",halls); - model.addAttribute("hallnames",hallnames); return "user/dashboard"; } - - //Checkavilability Api - @GetMapping("/checkAvail") - public String checkAvail(@RequestParam("fromDate") String fromDate, - @RequestParam("toDate") String toDate, - @RequestParam("starting") String starting, - @RequestParam("ending") String ending, - @RequestParam(name = "hallId", required = false) String hallId, - @RequestParam(name = "zone", required = false) String zone, - Model model) { - - List newnotification = notificationRepository.findActivenotifications(); - - // Create a string to concatenate all notifications descriptions - StringBuilder notificationText = new StringBuilder(); - - for (Notification notification : newnotification) { - notificationText.append(notification.getNotification_description()); - } - - // Pass the concatenated string to the model - model.addAttribute("newnotification", notificationText.toString()); - - List hallnames = hallDetailService.getHallNames(); - List hallsByZone; - int hallIdd = 0; - - // Parse hallId if provided - if (hallId != null && !hallId.isEmpty()) { - try { - hallIdd = Integer.parseInt(hallId); - } catch (NumberFormatException e) { - System.err.println("Invalid hallId: " + hallId); - } - } - - // Fetch halls by zone if zone is provided - if (zone != null && !zone.isEmpty()) { - hallsByZone = hallDetailsRepository.findByZone(zone); - } else { - hallsByZone = hallDetailsRepository.findActiveHalls(); - } - - // Fetch calendar data based on provided parameters - List data = calendarService.getCalendarByDateAndHallIdAndSlot(fromDate, toDate, starting, ending, hallIdd); - HashSet removeHallId = new HashSet<>(); - - // Collect hall IDs to be removed - for (BookingCalendar calendar : data) { - boolean isSameDay = fromDate.equals(toDate) && fromDate.equals(calendar.getBdate().toString()); - boolean isMorningStart = starting.equals("1"); - boolean isMorningEnd = ending.equals("1"); - boolean isEveningStart = starting.equals("2"); - boolean isEveningEnd = ending.equals("2"); - - if (isSameDay) { - // Same day booking cases - if (isMorningStart && isMorningEnd && (calendar.getBdate().toString().equals(fromDate) && calendar.isMorningSlot())) { - // System.out.println("Same day morning-morning match found: hallId=" + calendar.getHallId()); - removeHallId.add(calendar.getHallId()); - } else if (isEveningStart && isEveningEnd && (calendar.getBdate().toString().equals(fromDate) && calendar.isEveningSlot())) { - // System.out.println("Same day evening-evening match found: hallId=" + calendar.getHallId()); - removeHallId.add(calendar.getHallId()); - } else if (isMorningStart && isEveningEnd && - ((calendar.getBdate().toString().equals(fromDate) && calendar.isMorningSlot()) || - (calendar.getBdate().toString().equals(toDate) && calendar.isEveningSlot()))) { - // System.out.println("Same day morning-evening match found: hallId=" + calendar.getHallId()); - removeHallId.add(calendar.getHallId()); - } - } else { - // Multi-day booking cases - if ((isMorningStart && isMorningEnd) && - ((calendar.getBdate().toString().equals(fromDate) && calendar.isMorningSlot()) || - (calendar.getBdate().toString().equals(toDate) && calendar.isMorningSlot()))) { - // System.out.println("Multi-day morning-morning match found: hallId=" + calendar.getHallId()); - removeHallId.add(calendar.getHallId()); - } else if ((isEveningStart && isEveningEnd) && - ((calendar.getBdate().toString().equals(fromDate) && calendar.isEveningSlot()) || - (calendar.getBdate().toString().equals(toDate) && calendar.isEveningSlot()))) { - // System.out.println("Multi-day evening-evening match found: hallId=" + calendar.getHallId()); - removeHallId.add(calendar.getHallId()); - } else if (isMorningStart && isEveningEnd && - ((calendar.getBdate().toString().equals(fromDate) && calendar.isMorningSlot()) || - (calendar.getBdate().toString().equals(toDate) && calendar.isEveningSlot()))) { - // System.out.println("Multi-day morning-evening match found: hallId=" + calendar.getHallId()); - removeHallId.add(calendar.getHallId()); - } else if (isEveningStart && isMorningEnd && - ((calendar.getBdate().toString().equals(fromDate) && calendar.isEveningSlot()) || - (calendar.getBdate().toString().equals(toDate) && calendar.isMorningSlot()))) { - //System.out.println("Multi-day evening-morning match found: hallId=" + calendar.getHallId()); - removeHallId.add(calendar.getHallId()); - } - } - } - - // Remove unavailable halls from the list - hallsByZone.removeIf(hall -> removeHallId.contains(hall.getHallId())); - List removeHallById = new ArrayList<>(); - if (hallIdd != 0) { - HallDetails hallDetails = hallDetailService.getHallById(hallIdd); - // Ensure the hall is available before adding it to the list - if (!removeHallId.contains(hallIdd)) { - removeHallById.add(hallDetails); - } - } else { - removeHallById = hallDetailService.removeHallById(removeHallId); - } - - // Populate the model attributes - model.addAttribute("userName", userSession.getDispayName()); - model.addAttribute("hallnames", hallnames); - model.addAttribute("fromDate", fromDate); - model.addAttribute("toDate", toDate); - model.addAttribute("startingSlot", starting.equals("1") ? "Morning" : "Evening"); - model.addAttribute("endingSlot", ending.equals("1") ? "Morning" : "Evening"); - model.addAttribute("halls", (hallId != null && !hallId.isEmpty()) ? removeHallById : hallsByZone); - - return "user/dashboard"; - } - - - @PostMapping("/newregistrationform") - public String showRegistrationForm(@ModelAttribute("newform") Users newform,Model model) { - Users user = userService.user(newform); - userSession.setMobileno(user.getMobileNo()); - userSession.setDispayName(user.getName()); - userSession.setUserId(user.getUserId()); - userSession.setUserType(user.getUsertype().toString()); - System.out.println("usetrtype=="+user.getUsertype().toString()); - //System.out.println("employee id"+user.getGovernmentId()); - //System.out.println("employee id"+user.getDepartment()); - if (user.getUsertype() == userType.PUBLIC) { - String registersms="Welcome to GCC, Your User Registration for booking Community Centre is successful."; - String registerurlString ="https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to="+user.getMobileNo()+"&from=GCCCRP&body="+registersms+"&entityid=1401572690000011081&templateid=1407172346621223019"; - String registerwhatsupmsg="https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to="+user.getMobileNo()+"&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Welcome+to+GCC%2C+%0A%0AYour+User+Registration+for+booking+Community+Centre+is+successful."; - whatsappMsgServiceImpl.sendMsg(registerwhatsupmsg); - whatsappMsgServiceImpl.sendSMS(registerurlString); - }else { - String registerpendingsms="Welcome to GCC, Your User Registration request for booking Community Centre is submitted successfully."; - String registerpendingurlString ="https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to="+user.getMobileNo()+"&from=GCCCRP&body="+registerpendingsms+"&entityid=1401572690000011081&templateid=1407172346629919381"; - String registerpendingwhatsupmsg="https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to="+user.getMobileNo()+"&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Welcome+to+GCC%2C+%0A%0AYour+User+Registration+request+for+booking+Community+Centre+submitted+successfully."; - whatsappMsgServiceImpl.sendMsg(registerpendingwhatsupmsg); - whatsappMsgServiceImpl.sendSMS(registerpendingurlString); - } - return "redirect:/communityhall/dashboard"; - } - - @GetMapping("/hallbookingform") - public String viewform(Model model) { - String username = userSession.getDispayName(); - if (username != null) { - model.addAttribute("userName", username); - return "user/hallbookingform"; - } else { - return "redirect:/communityhall/dashboard"; - } - } - - @GetMapping("/viewhallform") - public String viewhallform(Model model) { - String username = userSession.getDispayName(); - model.addAttribute("userName", username); - return "user/viewhallform"; - - } - @GetMapping("/acknowledgement") - public String viewakowledgement(Model model, int bookingId) { - BookingDetails bookingsDetails = bookingService.getBookingsById(bookingId); - model.addAttribute("bookingsDetails",bookingsDetails); // Add single BookingDetails object - model.addAttribute("userName",userSession.getDispayName()); - return "user/acknowledgement"; - } - - @GetMapping("/logout") - public String logout(Model model) { - // Clear all login session (Check API Controller /gcc-login) - userSession.setUserId(null); - userSession.setMobileno(null); - userSession.setUserType(null); - userSession.setDispayName(null); - return "redirect:/communityhall/user/dashboard"; - } - - @GetMapping("/viewhistory") - public String viewBookingDetails(Model model,@RequestParam(name="bookingStatus",required = false)String bookingStatus) { - // Retrieve userId from session - Integer userId = userSession.getUserId(); - model.addAttribute("userName", userSession.getDispayName()); - - //List test = new ArrayList<>(); - model.addAttribute("userName", userSession.getDispayName()); - - List> bookingPast= bookingService.getAllBookingEventsByUserId(userId); - - model.addAttribute("userBookingspast",bookingPast); - - return "user/viewhistory"; - } - - @GetMapping("/CommunityHallList") - public String viewhalllist(Model model) { - model.addAttribute("userName",userSession.getDispayName()); - return "user/communityHallList"; - } - - @GetMapping("/hallAmountCalculation") - public String viewCalculate(Model model){ - model.addAttribute("userName",userSession.getDispayName()); - return "user/calculatehallamount"; - } - - @GetMapping("/collectionpending") - public String viewCollectionpending(Model model,int bookingId){ - BookingDetails bookingsDetails = bookingService.getBookingsById(bookingId); - model.addAttribute("bookingsDetails",bookingsDetails); // Add single BookingDetails object - model.addAttribute("userName",userSession.getDispayName()); - return "user/collectionpending"; - } - @GetMapping("/collectionpendingacknowledgement") - public String viewCollectionpendingAck(Model model,int bookingId){ - BookingDetails bookingsDetails = bookingService.getBookingsById(bookingId); - model.addAttribute("bookingsDetails",bookingsDetails); // Add single BookingDetails object - model.addAttribute("userName",userSession.getDispayName()); - return "user/extraebdamageamountack"; - } - + + + @PostMapping("/newregistrationform") + public String showRegistrationForm(@ModelAttribute("newform") Users newform, Model model) { + Users user = userService.user(newform); + userSession.setMobileno(user.getMobileNo()); + userSession.setDispayName(user.getName()); + userSession.setUserId(user.getUserId()); + userSession.setUserType(user.getUsertype().toString()); + System.out.println("usetrtype==" + user.getUsertype().toString()); + //System.out.println("employee id"+user.getGovernmentId()); + //System.out.println("employee id"+user.getDepartment()); + if (user.getUsertype() == userType.PUBLIC) { + String registersms = "Welcome to GCC, Your User Registration for booking Community Centre is successful."; + String registerurlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + user.getMobileNo() + "&from=GCCCRP&body=" + registersms + "&entityid=1401572690000011081&templateid=1407172346621223019"; + String registerwhatsupmsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + user.getMobileNo() + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Welcome+to+GCC%2C+%0A%0AYour+User+Registration+for+booking+Community+Centre+is+successful."; + whatsappMsgServiceImpl.sendMsg(registerwhatsupmsg); + whatsappMsgServiceImpl.sendSMS(registerurlString); + } else { + String registerpendingsms = "Welcome to GCC, Your User Registration request for booking Community Centre is submitted successfully."; + String registerpendingurlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + user.getMobileNo() + "&from=GCCCRP&body=" + registerpendingsms + "&entityid=1401572690000011081&templateid=1407172346629919381"; + String registerpendingwhatsupmsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + user.getMobileNo() + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Welcome+to+GCC%2C+%0A%0AYour+User+Registration+request+for+booking+Community+Centre+submitted+successfully."; + whatsappMsgServiceImpl.sendMsg(registerpendingwhatsupmsg); + whatsappMsgServiceImpl.sendSMS(registerpendingurlString); + } + return "redirect:/communityhall/dashboard"; + } + + @GetMapping("/hallbookingform") + public String viewform(Model model) { + String username = userSession.getDispayName(); + model.addAttribute("userName", username); + return "user/hallbookingform"; + } + + @GetMapping("/acknowledgement") + public String viewakowledgement(Model model, int bookingId) { + BookingDetails bookingsDetails = bookingService.getBookingsById(bookingId); + model.addAttribute("bookingsDetails", bookingsDetails); // Add single BookingDetails object + model.addAttribute("userName", userSession.getDispayName()); + return "user/acknowledgement"; + } + + @GetMapping("/logout") + public String logout(Model model) { + // Clear all login session (Check API Controller /gcc-login) + userSession.setUserId(null); + userSession.setMobileno(null); + userSession.setUserType(null); + userSession.setDispayName(null); + return "redirect:/communityhall/user/dashboard"; + } + + @GetMapping("/viewhistory") + public String viewBookingDetails(Model model, @RequestParam(name = "bookingStatus", required = false) String bookingStatus) { + // Retrieve userId from session + Integer userId = userSession.getUserId(); + model.addAttribute("userName", userSession.getDispayName()); + + //List test = new ArrayList<>(); + model.addAttribute("userName", userSession.getDispayName()); + + List> bookingPast = bookingService.getAllBookingEventsByUserId(userId); + + model.addAttribute("userBookingspast", bookingPast); + + return "user/viewhistory"; + } + + @GetMapping("/CommunityHallList") + public String viewhalllist(Model model) { + model.addAttribute("userName", userSession.getDispayName()); + return "user/communityHallList"; + } + + @GetMapping("/hallAmountCalculation") + public String viewCalculate(Model model) { + model.addAttribute("userName", userSession.getDispayName()); + return "user/calculatehallamount"; + } + + @GetMapping("/collectionpending") + public String viewCollectionpending(Model model, int bookingId) { + BookingDetails bookingsDetails = bookingService.getBookingsById(bookingId); + model.addAttribute("bookingsDetails", bookingsDetails); // Add single BookingDetails object + model.addAttribute("userName", userSession.getDispayName()); + return "user/collectionpending"; + } + + @GetMapping("/collectionpendingacknowledgement") + public String viewCollectionpendingAck(Model model, int bookingId) { + BookingDetails bookingsDetails = bookingService.getBookingsById(bookingId); + model.addAttribute("bookingsDetails", bookingsDetails); // Add single BookingDetails object + model.addAttribute("userName", userSession.getDispayName()); + return "user/extraebdamageamountack"; + } + + @GetMapping("/viewhallform") + public String viewhallform(Model model) { + String username = userSession.getDispayName(); + model.addAttribute("userName", username); + return "user/viewhallform"; + + } + } diff --git a/src/main/java/com/gcc/communityHall/entity/BookingCalendar.java b/src/main/java/com/gcc/communityHall/entity/BookingCalendar.java index bf6a9234..b807ca36 100644 --- a/src/main/java/com/gcc/communityHall/entity/BookingCalendar.java +++ b/src/main/java/com/gcc/communityHall/entity/BookingCalendar.java @@ -20,9 +20,9 @@ public class BookingCalendar { private boolean is_active; private boolean is_delete; private int is_booked; - private boolean is_blocked = false; - private boolean temp_blocked = false; + + private int hallId; public Integer getId() { @@ -33,14 +33,11 @@ public class BookingCalendar { this.id = id; } - public boolean getIs_blocked() { - return is_blocked; - } - public void setIs_blocked(boolean is_blocked) { - this.is_blocked = is_blocked; - } - public LocalDate getBdate() { + + + + public LocalDate getBdate() { return bdate; } @@ -112,22 +109,21 @@ public class BookingCalendar { this.hallId = hallId; } - public boolean isTemp_blocked() { - return temp_blocked; + public boolean getIs_blocked() { + return is_blocked; } - public void setTemp_blocked(boolean temp_blocked) { - this.temp_blocked = temp_blocked; + public void setIs_blocked(boolean is_blocked) { + this.is_blocked = is_blocked; } - public BookingCalendar() { + public BookingCalendar() { super(); // TODO Auto-generated constructor stub } public BookingCalendar(Integer id, LocalDate bdate, boolean morningSlot, boolean eveningSlot, String bookingId_1, - String bookingId_2, boolean is_active, boolean is_delete, int is_booked,boolean is_blocked, - boolean temp_blocked, int hallId) { + String bookingId_2, boolean is_active, boolean is_delete, int is_booked, boolean is_blocked, int hallId) { super(); this.id = id; this.bdate = bdate; @@ -139,7 +135,6 @@ public class BookingCalendar { this.is_delete = is_delete; this.is_booked = is_booked; this.is_blocked = is_blocked; - this.temp_blocked = temp_blocked; this.hallId = hallId; } diff --git a/src/main/java/com/gcc/communityHall/paymentService/controller/PaymentAPIController.java b/src/main/java/com/gcc/communityHall/paymentService/controller/PaymentAPIController.java index db8dc2d4..24d70a96 100644 --- a/src/main/java/com/gcc/communityHall/paymentService/controller/PaymentAPIController.java +++ b/src/main/java/com/gcc/communityHall/paymentService/controller/PaymentAPIController.java @@ -5,7 +5,6 @@ import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.Optional; -import com.gcc.communityHall.service.Impl.BookingServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.ui.Model; @@ -60,9 +59,6 @@ public class PaymentAPIController { @Autowired private TransactionNumberGenerator transactionNumber; - @Autowired - private BookingServiceImpl bookingService; - // @Operation( // summary = "Refund the Total Amount REST API", @@ -132,59 +128,53 @@ public class PaymentAPIController { summary = "payment-request REST API", description = "REST API payment-request" ) - @PostMapping(value = {"/payment-request"}) - public HashMap startPayment(int userId, int bookingId) throws NoSuchAlgorithmException { - - //System.out.println("I entered payment Service......"+bookingId+ "User Id :- "+userId); - HashMap hs = new HashMap<>(); - Optional findById = bookRepo.findById(bookingId); - - if (findById.isPresent()) { - //System.out.println("Success in finding booking Id"); - BookingDetails booking = findById.get(); - Users user = booking.getUsers(); - int findUserId = user.getUserId(); - - boolean slotStatus = bookingService.isSlotOccupied(booking); - System.out.println("slot status: " + slotStatus); - //System.out.println("Merchant ID:-"+this.paymentConfig.getMerchantId()); - if(!slotStatus){ - String txnId = "CHB" + transactionNumber.generateTransactionNumber() + String.format("%05d", findUserId); //create transaction Id unique from our side - String totalAmt = String.valueOf(booking.getAmountReceived()); //Amount of Community Hall from our side - TransactionResponse response = new TransactionResponse(); - response.setTxansactionId(txnId); - response.setHallId(booking.getHallDetails().getHallId()); - response.setUserId(String.valueOf(findUserId));//make it dynamic - response.setStatusCode("temp"); - response.setBookingId(bookingId); - this.paymentService.recordResponse(response); - - String merchantId = this.paymentConfig.getMerchantId(); //This is Test Merchant ID from worldLine - String consumerId = String.format("%05d", findUserId); // Replace consumer ID in c964634 from our side - String consumerMobileNo = String.valueOf(user.getMobileNo()); //Replace consumer Mobile no in 9879879870 from our side - String consumerEmailId = user.getEmail(); //replace consumer email Id - - String encryptedtoken = this.paymentService.getToken(merchantId + "|", txnId + "|", totalAmt + "|", "|", consumerId + "|", consumerMobileNo + "|", consumerEmailId + "|", "|", "|", "|", "|", "|", "|", "|", "|", "|", this.paymentConfig.getEncryptionKey()); - - hs.put("txansactionId", txnId); - hs.put("token", encryptedtoken); - hs.put("amount", totalAmt); - hs.put("merchantId", merchantId); - hs.put("consumerMobileNo", consumerMobileNo); - hs.put("consumerEmailId", consumerEmailId); - hs.put("consumerId", consumerId); - hs.put("error", false); - } else{ - hs.put("status", "slotOccupied"); - return hs; - } - - } else { - hs.put("error", true); - } - - return hs; - } + @PostMapping(value = {"/payment-request"}) + public HashMap startPayment(int userId,int bookingId) throws NoSuchAlgorithmException { + + //System.out.println("I entered payment Service......"+bookingId+ "User Id :- "+userId); + HashMap hs = new HashMap<>(); + Optional findById = bookRepo.findById(bookingId); + + if(findById.isPresent()) { + //System.out.println("Success in finding booking Id"); + BookingDetails booking = findById.get(); + Users user = booking.getUsers(); + int findUserId=user.getUserId(); + //System.out.println("Merchant ID:-"+this.paymentConfig.getMerchantId()); + + String txnId="CHB"+transactionNumber.generateTransactionNumber()+String.format("%05d", findUserId); //create transaction Id unique from our side + String totalAmt = String.valueOf(booking.getAmountReceived()); //Amount of Community Hall from our side + TransactionResponse response = new TransactionResponse(); + response.setTxansactionId(txnId); + response.setHallId(booking.getHallDetails().getHallId()); + response.setUserId(String.valueOf(findUserId));//make it dynamic + response.setStatusCode("temp"); + response.setBookingId(bookingId); + this.paymentService.recordResponse(response); + + + String merchantId = this.paymentConfig.getMerchantId(); //This is Test Merchant ID from worldLine + String consumerId=String.format("%05d", findUserId); // Replace consumer ID in c964634 from our side + String consumerMobileNo=String.valueOf(user.getMobileNo()); //Replace consumer Mobile no in 9879879870 from our side + String consumerEmailId=user.getEmail(); //replace consumer email Id + + String encryptedtoken = this.paymentService.getToken(merchantId+"|", txnId+"|", totalAmt+"|", "|", consumerId+"|", consumerMobileNo+"|", consumerEmailId+"|", "|", "|", "|", "|", "|", "|", "|", "|", "|", this.paymentConfig.getEncryptionKey()); + + hs.put("txansactionId",txnId); + hs.put("token",encryptedtoken); + hs.put("amount",totalAmt); + hs.put("merchantId",merchantId); + hs.put("consumerMobileNo",consumerMobileNo); + hs.put("consumerEmailId",consumerEmailId); + hs.put("consumerId",consumerId); + hs.put("error", false); + } + else { + hs.put("error", true); + } + + return hs; + } @Operation( summary = "Additional Damage payment-request REST API", diff --git a/src/main/java/com/gcc/communityHall/paymentService/controller/PaymentController.java b/src/main/java/com/gcc/communityHall/paymentService/controller/PaymentController.java index ef48aaa6..0a276a7e 100644 --- a/src/main/java/com/gcc/communityHall/paymentService/controller/PaymentController.java +++ b/src/main/java/com/gcc/communityHall/paymentService/controller/PaymentController.java @@ -118,7 +118,6 @@ public class PaymentController { TransactionResponse save = transactionResRepo.save(response); if(paymentService.generateToken(c).equals(confirmToken) && status.equals(res[0])){ - payment.setPaymentType(res[11]); payment.setPaymentStatus("Success"); bookingsDetails.setPayments(payment); String confirmBooking = bookser.confirmBooking(response.getBookingId()); @@ -205,7 +204,6 @@ public class PaymentController { if(paymentService.generateToken(c).equals(confirmToken) && status.equals(res[0])){ payment.setPaymentStatus("Success"); - payment.setPaymentType(res[11]); bookingsDetails.setExtrapayments(payment); bookingsDetails.getSettlement().setCollectionStatus("Paid"); bookingsDetails.setBookingStatus(BookingStatus.COMPLETED); 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 b2948a1a..75769995 100644 --- a/src/main/java/com/gcc/communityHall/paymentService/repository/TransactionResponseRepository.java +++ b/src/main/java/com/gcc/communityHall/paymentService/repository/TransactionResponseRepository.java @@ -24,20 +24,8 @@ public interface TransactionResponseRepository extends JpaRepository findByTxansactionIdAndStatusCode(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 " + - "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 booking_details bd ON tr.booking_id = bd.booking_id " + - "WHERE DATE(bd.booking_date) between :fromDate and :toDate " + - "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); -/* + @Query(value = "SELECT tr.booking_id, tr.hall_id, tr.amount, tr.status_code, tr.txansaction_id, tr.user_id, p.payment_status " + "FROM transaction_response tr " + "JOIN hall_details hd ON tr.hall_id = hd.hall_id " + @@ -51,7 +39,7 @@ public interface TransactionResponseRepository extends JpaRepository bookingsDetails=bookingDetailsRepository.findById(bookingId); BookingDetails bookingDetails=bookingsDetails.get(); @@ -321,8 +320,7 @@ public class PaymentGatewayServiceImpl implements PaymentGatewayService { recordRefundResponse.setBalaceAmount(myObject.getPaymentMethod().getPaymentTransaction().getBalanceAmount()); this.recordRefund(recordRefundResponse); RefundTransaction refundTransaction=new RefundTransaction(); - double refundAmount = Double.parseDouble(recordRefundResponse.getAmount()) - Double.parseDouble(recordRefundResponse.getBalaceAmount()); - refundTransaction.setAmountRefunded(refundAmount); + refundTransaction.setAmountRefunded(Double.parseDouble(recordRefundResponse.getAmount())); refundTransaction.setCdate(new Date()); Optional bookingsDetails=bookingDetailsRepository.findById(bookingId); BookingDetails bookingDetails=bookingsDetails.get(); @@ -349,7 +347,7 @@ public class PaymentGatewayServiceImpl implements PaymentGatewayService { Optional bookings=bookingDetailsRepository.findById(bookingId); BookingDetails bookingdetails= null; if(bookings.isPresent()) { - bookingdetails=bookings.get(); + bookingdetails=bookings.get(); if((bookingdetails.getBookingStatus() == BookingDetails.BookingStatus.REFUNDED) && (bookingdetails.getRefundStatus() == RefundStatus.COMPLETED)) { return "Error"; @@ -413,8 +411,7 @@ public class PaymentGatewayServiceImpl implements PaymentGatewayService { bookingdetails.setRefundStatus(RefundStatus.COMPLETED); bookingDetailsRepository.save(bookingdetails); RefundTransaction refundTransaction=new RefundTransaction(); - double refundAmount = Double.parseDouble(recordRefundResponse.getAmount()) - Double.parseDouble(recordRefundResponse.getBalaceAmount()); - refundTransaction.setAmountRefunded(refundAmount); + refundTransaction.setAmountRefunded(Double.parseDouble(recordRefundResponse.getAmount())); refundTransaction.setCdate(new Date()); refundTransaction.setBookingDetails(bookingdetails); refundTransaction.setRefundIdentifier(myObject.getPaymentMethod().getPaymentTransaction().getRefundIdentifier()); diff --git a/src/main/java/com/gcc/communityHall/repository/BookingCalendarRepository.java b/src/main/java/com/gcc/communityHall/repository/BookingCalendarRepository.java index 83e89010..98a70e45 100644 --- a/src/main/java/com/gcc/communityHall/repository/BookingCalendarRepository.java +++ b/src/main/java/com/gcc/communityHall/repository/BookingCalendarRepository.java @@ -5,7 +5,6 @@ import java.util.List; import java.util.Map; import java.util.Optional; -import jakarta.transaction.Transactional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; @@ -13,7 +12,6 @@ import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import com.gcc.communityHall.entity.BookingCalendar; -import com.gcc.communityHall.entity.BookingDetails; @Repository public interface BookingCalendarRepository extends JpaRepository { @@ -62,17 +60,6 @@ public interface BookingCalendarRepository extends JpaRepository 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 " + - "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))", - nativeQuery = true) -List findBookingCalendarDetails(@Param("fromDate") String fromDate, - @Param("toDate") String toDate, - @Param("bookingId") Long bookingId);*/ - @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 " + @@ -86,10 +73,4 @@ List findBookingCalendarDetails(@Param("fromDate") String fromDate, @Param("bookingId") Long bookingId, @Param("hallName") String hallName); - - @Modifying - @Transactional - @Query("UPDATE BookingCalendar bc set bc.temp_blocked = :tempBlock WHERE (bc.id =:finalBcid)") - void updateTempBlocked(int finalBcid, boolean tempBlock); - } diff --git a/src/main/java/com/gcc/communityHall/repository/BookingDetailsRepository.java b/src/main/java/com/gcc/communityHall/repository/BookingDetailsRepository.java index 42ce7479..220feaa8 100644 --- a/src/main/java/com/gcc/communityHall/repository/BookingDetailsRepository.java +++ b/src/main/java/com/gcc/communityHall/repository/BookingDetailsRepository.java @@ -13,63 +13,63 @@ import org.springframework.stereotype.Repository; import com.gcc.communityHall.entity.BookingDetails; import com.gcc.communityHall.entity.BookingDetails.BookingStatus; -import com.gcc.communityHall.entity.CounterRefundList; import com.gcc.communityHall.entity.HallDetails; -import com.gcc.communityHall.entity.Users; @Repository -public interface BookingDetailsRepository extends JpaRepository { +public interface BookingDetailsRepository extends JpaRepository { @Query(value = "SELECT * FROM booking_details where booking_status='GCC_BLOCKED'", nativeQuery = true) - List getGccBlockedList(); + List getGccBlockedList(); + @Query(value = "SELECT * FROM booking_details where booking_status='APPROVED'", nativeQuery = true) - List getAllApprovedList(); - - @Query(value = "SELECT * FROM booking_details where booking_status='REJECTED'", nativeQuery = true) - List getAllRejectingList(); + List getAllApprovedList(); + @Query(value = "SELECT * FROM booking_details where booking_status='REJECTED'", nativeQuery = true) + List getAllRejectingList(); - @Query(value = "SELECT * FROM booking_details where booking_status='WAITING_FOR_NOC' order by booking_id", nativeQuery = true) - List getAllwaitingNOC(); @Query(value = "SELECT * FROM booking_details where booking_status='WAITING_FOR_NOC_APPROVAL'", nativeQuery = true) - List getAllwaitingList(); - - @Query(value = "SELECT * FROM booking_details WHERE hall_details_hall_id IN (:hallIds) AND booking_status IN ('APPROVED') AND start_date BETWEEN :fromDate AND :toDate ", nativeQuery = true) + List getAllwaitingList(); + + @Query(value = "SELECT * FROM booking_details WHERE hall_details_hall_id IN (:hallIds) AND " + + "booking_status IN ('APPROVED','WAITING_FOR_NOC','WAITING_FOR_NOC_APPROVAL') AND " + + "((start_date BETWEEN :fromDate AND :toDate) or (end_date BETWEEN :fromDate AND :toDate))", nativeQuery = true) List findByFromDateBetweenAndToDateBetweenAndHallIdIn(LocalDate fromDate, LocalDate toDate, List hallIds); - + @Query("SELECT b FROM BookingDetails b JOIN FETCH b.settlement s WHERE s.settlementId = :settlementId") BookingDetails findBySettlementIdWithBookingDetails(@Param("settlementId") int settlementId); - @Query("SELECT bd FROM BookingDetails bd JOIN bd.hallDetails hd WHERE hd.zone = :zone AND bd.bookingStatus IN ('WAITING_FOR_NOC')") - List getWaitinglist(@Param("zone") String zone); + @Query("SELECT bd FROM BookingDetails bd JOIN bd.hallDetails hd WHERE hd.zone = :zone AND bd.bookingStatus IN ('WAITING_FOR_NOC')") + List getWaitinglist(@Param("zone") String zone); - @Query("SELECT bd FROM BookingDetails bd JOIN bd.hallDetails hd WHERE hd.zone = :zone AND bd.bookingStatus IN ('APPROVED')") - List getApprovedlist(@Param("zone") String zone); + @Query("SELECT bd FROM BookingDetails bd JOIN bd.hallDetails hd WHERE hd.zone = :zone AND bd.bookingStatus IN ('APPROVED')") + List getApprovedlist(@Param("zone") String zone); - @Query("SELECT bd FROM BookingDetails bd JOIN bd.hallDetails hd WHERE hd.zone = :zone AND bd.bookingStatus IN ('REJECTED')") - List getrejectedlist(@Param("zone") String zone); + @Query("SELECT bd FROM BookingDetails bd JOIN bd.hallDetails hd WHERE hd.zone = :zone AND bd.bookingStatus IN ('REJECTED')") + List getrejectedlist(@Param("zone") String zone); - @Query("SELECT bd FROM BookingDetails bd JOIN bd.hallDetails hd WHERE hd.zone = :zone AND bd.bookingStatus IN ('PENDING', 'PAYMENT_FAILURE')") - List getPendingOrPaymentFailureBookings(@Param("zone") String zone); + @Query("SELECT bd FROM BookingDetails bd JOIN bd.hallDetails hd WHERE hd.zone = :zone AND bd.bookingStatus IN ('PENDING', 'PAYMENT_FAILURE')") + List getPendingOrPaymentFailureBookings(@Param("zone") String zone); - @Query(value = "SELECT * FROM booking_details WHERE DATE(start_date) = CURRENT_DATE() AND hall_details_hall_id = :hallId and booking_status='APPROVED'", nativeQuery = true) - List findPresentsEventsByUserId(Integer hallId); - //List findpresentseventsByHallid(Integer hallId); + @Query(value = "SELECT * FROM booking_details WHERE DATE(start_date) = CURRENT_DATE() AND hall_details_hall_id = :hallId and booking_status='APPROVED'", nativeQuery = true) + List findPresentsEventsByUserId(Integer hallId); + //List findpresentseventsByHallid(Integer hallId); -// @Query(value = "SELECT * FROM booking_details WHERE DATE(start_date) < CURRENT_DATE() AND hall_details_hall_id = :hallId and booking_status='APPROVED'", nativeQuery = true) + // @Query(value = "SELECT * FROM booking_details WHERE DATE(start_date) < CURRENT_DATE() AND hall_details_hall_id = :hallId and booking_status='APPROVED'", nativeQuery = true) // List findPastsEventsByUserId(Integer hallId); // @Query(value = "SELECT * FROM booking_details WHERE DATE(start_date) < CURRENT_DATE() AND hall_details_hall_id = :hallId AND booking_status = 'APPROVED'", nativeQuery = true) // List findPastEventsByHallId(Integer hallId); -@Query(value = "SELECT * FROM booking_details WHERE DATE(start_date) < CURRENT_DATE() AND hall_details_hall_id = :hallId AND booking_status = 'APPROVED'", nativeQuery = true) -List findPastEventsByHallId(@Param("hallId") Integer hallId); +/* @Query(value = "SELECT * FROM booking_details WHERE DATE(start_date) BETWEEN DATE_SUB(CURRENT_DATE(), INTERVAL 2 DAY) AND CURRENT_DATE() - INTERVAL 1 DAY AND hall_details_hall_id = :hallId AND booking_status = 'APPROVED'", nativeQuery = true) + List findPastEventsByHallId(@Param("hallId") Integer hallId);*/ + @Query(value = "SELECT * FROM booking_details WHERE DATE(start_date) < CURRENT_DATE() AND hall_details_hall_id = :hallId AND booking_status = 'APPROVED'", nativeQuery = true) + List findPastEventsByHallId(@Param("hallId") Integer hallId); - @Query(value = "SELECT * FROM booking_details " + - "WHERE DATE(start_date) BETWEEN DATE_ADD(CURRENT_DATE(), INTERVAL 1 DAY) AND DATE_ADD(CURRENT_DATE(), INTERVAL 2 DAY) " + - "AND hall_details_hall_id = :hallId " + - "AND booking_status = 'APPROVED'", nativeQuery = true) - List findFutureEventsByHallId(Integer hallId); + @Query(value = "SELECT * FROM booking_details " + + "WHERE DATE(start_date) BETWEEN DATE_ADD(CURRENT_DATE(), INTERVAL 1 DAY) AND DATE_ADD(CURRENT_DATE(), INTERVAL 2 DAY) " + + "AND hall_details_hall_id = :hallId " + + "AND booking_status = 'APPROVED'", nativeQuery = true) + List findFutureEventsByHallId(Integer hallId); // @Query(value = "SELECT * FROM booking_details " + // "WHERE DATE(start_date) > CURRENT_DATE() " + // "AND hall_details_hall_id = :hallId " + @@ -77,153 +77,158 @@ List findPastEventsByHallId(@Param("hallId") Integer hallId); // List findFutureEventsByHallId(Integer hallId); - @Query(value = "select count(users_user_id), us.user_status from booking_details bd inner join users us on us.user_id = bd.users_user_id \r\n" - + "where users_user_id=:userId and booking_status in ('APPROVED','COMPLETED','WAITING_FOR_NOC') and DATE_SUB(CURDATE(), INTERVAL 1 YEAR) \r\n" - + "and us.user_status not in ('PENDING')", nativeQuery = true) - int checkUserBookinglimitation(int userId); - @Query(value = "SELECT * FROM booking_details WHERE users_user_id = :userId AND booking_status NOT IN ('PENDING')", nativeQuery = true) - List getAllBookingsByUserId(Integer userId); - - @Query(value="select * from booking_details WHERE booking_id =:bookID", nativeQuery = true) - BookingDetails getByBookingId(String bookID); - // + " WHERE hall_details_hall_id =:hallId and booking_status= 'APPROVED' and start_date < curdate() ", nativeQuery = true) - @Query(value = "SELECT * FROM booking_details WHERE DATE(start_date) <= CURRENT_DATE() AND hall_details_hall_id = :hallId and booking_status='APPROVED' and refund_status IN ('WAITING','REJECTED','APPROVED')", nativeQuery = true) - public List getSettlementList(Integer hallId); - - //yoga - @Query(value = "SELECT " + - "u.user_id AS userId, " + - "u.name AS UserName, " + - "u.mobile_no AS MobileNumber, " + - "CONCAT(u.doorno,',',u.street, ', ', u.area, ', ', u.location, ', ', u.pin_code) AS Address, " + - "COUNT(*) AS TotalBookings, " + - "SUM(CASE WHEN bd.booking_status = 'APPROVED' THEN 1 ELSE 0 END) AS Payment, " + - "SUM(CASE WHEN bd.booking_status = 'REJECTED' THEN 1 ELSE 0 END) AS Rejected, " + - "SUM(CASE WHEN bd.booking_status = 'CANCELED' THEN 1 ELSE 0 END) AS Canceled, " + - "SUM(CASE WHEN bd.booking_status = 'PAYMENT_FAILURE' THEN 1 ELSE 0 END) AS PaymentFailure " + - "FROM " + - "booking_details bd " + - "JOIN " + - "users u ON bd.users_user_id = u.user_id " + - "WHERE DATE(bd.booking_date) >= :fromDate "+ - "AND DATE(bd.booking_date) <= :toDate " + - "AND bd.booking_status NOT IN ('PENDING')"+ - "GROUP BY " + - "bd.users_user_id", nativeQuery = true) - List getBookingUserDetailsReport(@Param("fromDate") String fromDate, @Param("toDate") String toDate); - - - - @Query(value = "SELECT " + - "h.hall_name AS HallName, " + - "h.hall_Incharge_name AS InchargeName, " + - "h.hall_Incharge_no AS hallInchargeMobno, " + - "CONCAT(h.zone, '/', h.division) AS ZoneDivision, " + // Concatenate zone and division - "COUNT(*) AS HallTotalBookings, " + - "SUM(p.amount_received) AS AmountReceived, " + - "COALESCE(SUM(r.amount - r.balace_amount), 0) AS AmountRefund, " + - "COALESCE(SUM(CASE WHEN bd.booking_status IN ('COMPLETED', 'CANCELED') THEN r.balace_amount ELSE 0 END), 0) AS Difference " + - "FROM " + - "booking_details bd " + - "JOIN " + - "hall_details h ON bd.hall_details_hall_id = h.hall_id " + - "LEFT JOIN users u ON bd.users_user_id = u.user_id "+ - "JOIN " + - "payments p ON bd.booking_id = p.booking_details_booking_id " + - "LEFT JOIN refund_response r ON bd.booking_id = r.booking_id " + - "WHERE DATE(bd.booking_date) >= :fromDate " + - "AND DATE(bd.booking_date) <= :toDate " + - "AND bd.booking_status NOT IN ('PENDING')"+ - "GROUP BY " + - "bd.hall_details_hall_id", nativeQuery = true) - List getBookingHallDetailsReport(@Param("fromDate") String fromDate, @Param("toDate") String toDate); - - @Query(value="SELECT \r\n" - + " COALESCE( SUM(\r\n" - + " CASE \r\n" - + " WHEN start_date = CURDATE() THEN 1\r\n" - + " ELSE 0\r\n" - + " END\r\n" - + " ),0) AS currente,\r\n" - + " COALESCE( SUM(\r\n" - + " CASE \r\n" - + " \r\n" - + " WHEN start_date < CURDATE() THEN 1\r\n" - + " ELSE 0\r\n" - + " END\r\n" - + " ), 0) AS past,\r\n" - + " COALESCE( SUM(\r\n" - + " CASE \r\n" - + " \r\n" - + " WHEN start_date > CURDATE() THEN 1\r\n" - + " ELSE 0\r\n" - + " END\r\n" - + " ),0) AS FUTURE\r\n" - + "FROM \r\n" - + " booking_details hall\r\n" - + " where hall_details_hall_id= :hall_id and booking_status='APPROVED'",nativeQuery = true) - List> pieChartCount(int hall_id); - - //@Query(value = "SELECT * FROM booking_details WHERE DATE(booking_date) >= :fromDate AND DATE(booking_date) <= :toDate AND (:bookingStatus IS NULL OR booking_status = :bookingStatus)", nativeQuery = true) - @Query(value = "SELECT bd.booking_id, bd.booking_date, hd.hall_name, us.name, us.mobile_no, " + - "CONCAT(us.doorno, ', ', us.street, ', ', us.area, ', ', us.location, ', ', us.pin_code) AS address, " + - "us.usertype, bd.reason, bd.start_date, bd.end_date, " + - "(bd.deposit_amount + bd.hall_amount + bd.gst) AS amount_paid, bd.booking_status " + - "FROM booking_details bd " + - "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + - "JOIN users us ON bd.users_user_id = us.user_id " + - "WHERE DATE(bd.booking_date) >= :fromDate " + - "AND DATE(bd.booking_date) <= :toDate " + - "AND (:bookingStatus IS NULL OR bd.booking_status = :bookingStatus) ", - nativeQuery = true) - List getAllBookingDetailsWithStatus(@Param("fromDate") String fromDate, - @Param("toDate") String toDate, - @Param("bookingStatus") String bookingStatus); - - @Query(value = "SELECT bd.booking_id, bd.booking_date, hd.hall_name, us.name, us.mobile_no, " + - "CONCAT(us.doorno, ', ', us.street, ', ', us.area, ', ', us.location, ', ', us.pin_code) AS address, " + - "us.usertype, bd.reason, bd.start_date, bd.end_date, " + - "bd.deposit_amount, bd.hall_amount, bd.gst, bd.amount_received, bd.booking_status " + - "FROM booking_details bd " + - "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + - "JOIN users us ON bd.users_user_id = us.user_id " + - "WHERE DATE(bd.booking_date) >= :fromDate " + - "AND DATE(bd.booking_date) <= :toDate " + - "AND (:bookingId IS NULL OR bd.booking_id = :bookingId)", - nativeQuery = true) - List getAllBookingDetailsWithBookingId(@Param("fromDate") String fromDate, - @Param("toDate") String toDate, - @Param("bookingId") Long bookingId); - - @Query(value = "SELECT bd.booking_id, bd.booking_date, hd.hall_name, us.name, us.mobile_no, " + - "CONCAT(us.doorno, ', ', us.street, ', ', us.area, ', ', us.location, ', ', us.pin_code) AS address, " + - "us.usertype, bd.reason, bd.start_date, bd.end_date, " + - "bd.deposit_amount, bd.hall_amount, bd.gst, bd.amount_received, bd.booking_status " + - "FROM booking_details bd " + - "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + - "JOIN users us ON bd.users_user_id = us.user_id " + - "WHERE DATE(bd.booking_date) >= :fromDate " + - "AND DATE(bd.booking_date) <= :toDate " + - "AND (:bookingId IS NULL OR bd.booking_id = :bookingId)" + - "AND (:bookingStatus IS NULL OR bd.booking_status = :bookingStatus)", - nativeQuery = true) - List getAllBookingDetailsWithBookingIdwithbookingStatus(@Param("fromDate") String fromDate, - @Param("toDate") String toDate, - @Param("bookingId") Long bookingId, @Param("bookingStatus") String bookingStatus); - - //@Query(value = "SELECT * FROM booking_details WHERE DATE(booking_date) >= :fromDate AND DATE(booking_date) <= :toDate", nativeQuery = true) - @Query(value = "SELECT bd.booking_id, bd.booking_date, hd.hall_name, us.name, us.mobile_no, " + - "CONCAT(us.doorno, ', ', us.street, ', ', us.area, ', ', us.location, ', ', us.pin_code) AS address, " + - "us.usertype, bd.reason, bd.start_date, bd.end_date, " + - "(bd.deposit_amount + bd.hall_amount + bd.gst) AS amount_paid, bd.booking_status " + - "FROM booking_details bd " + - "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + - "JOIN users us ON bd.users_user_id = us.user_id " + - "WHERE DATE(bd.booking_date) >= :fromDate " + - "AND DATE(bd.booking_date) <= :toDate ", - nativeQuery = true) - List getAllBookingDetails(@Param("fromDate") String fromDate, @Param("toDate") String toDate); - + @Query(value = "select count(users_user_id), us.user_status from booking_details bd inner join users us on us.user_id = bd.users_user_id \r\n" + + "where users_user_id=:userId and booking_status in ('APPROVED','COMPLETED','WAITING_FOR_NOC','WAITING_FOR_NOC_APPROVAL') and DATE_SUB(CURDATE(), INTERVAL 1 YEAR) \r\n" + + "and us.user_status not in ('PENDING')", nativeQuery = true) + int checkUserBookinglimitation(int userId); + + @Query(value = "SELECT * FROM booking_details WHERE users_user_id = :userId AND booking_status NOT IN ('PENDING')", nativeQuery = true) + List getAllBookingsByUserId(Integer userId); + + @Query(value = "select * from booking_details WHERE booking_id =:bookID", nativeQuery = true) + BookingDetails getByBookingId(String bookID); + + // + " WHERE hall_details_hall_id =:hallId and booking_status= 'APPROVED' and start_date < curdate() ", nativeQuery = true) + @Query(value = "SELECT * FROM booking_details WHERE DATE(start_date) <= CURRENT_DATE() AND hall_details_hall_id = :hallId and booking_status='APPROVED' and refund_status IN ('WAITING','REJECTED','APPROVED')", nativeQuery = true) + public List getSettlementList(Integer hallId); + + @Query(value = "SELECT * FROM booking_details WHERE DATE(start_date) <= CURRENT_DATE() AND booking_status='APPROVED' AND refund_status IN ('WAITING','REJECTED','APPROVED')", nativeQuery = true) + public List getAllSettlementList(); + + + //yoga + @Query(value = "SELECT " + + "u.user_id AS userId, " + + "u.name AS UserName, " + + "u.mobile_no AS MobileNumber, " + + "CONCAT(u.doorno,',',u.street, ', ', u.area, ', ', u.location, ', ', u.pin_code) AS Address, " + + "COUNT(*) AS TotalBookings, " + + "SUM(CASE WHEN bd.booking_status = 'APPROVED' THEN 1 ELSE 0 END) AS Payment, " + + "SUM(CASE WHEN bd.booking_status = 'REJECTED' THEN 1 ELSE 0 END) AS Rejected, " + + "SUM(CASE WHEN bd.booking_status = 'CANCELED' THEN 1 ELSE 0 END) AS Canceled, " + + "SUM(CASE WHEN bd.booking_status = 'PAYMENT_FAILURE' THEN 1 ELSE 0 END) AS PaymentFailure " + + "FROM " + + "booking_details bd " + + "JOIN " + + "users u ON bd.users_user_id = u.user_id " + + "WHERE DATE(bd.booking_date) >= :fromDate " + + "AND DATE(bd.booking_date) <= :toDate " + + "AND bd.booking_status NOT IN ('PENDING')" + + "GROUP BY " + + "bd.users_user_id", nativeQuery = true) + List getBookingUserDetailsReport(@Param("fromDate") String fromDate, @Param("toDate") String toDate); + + + @Query(value = "SELECT " + + "h.hall_name AS HallName, " + + "h.hall_Incharge_name AS InchargeName, " + + "h.hall_Incharge_no AS hallInchargeMobno, " + + "CONCAT(h.zone, '/', h.division) AS ZoneDivision, " + // Concatenate zone and division + "COUNT(*) AS HallTotalBookings, " + + "SUM(p.amount_received) AS AmountReceived, " + + "COALESCE(SUM(r.amount - r.balace_amount), 0) AS AmountRefund, " + + "COALESCE(SUM(CASE WHEN bd.booking_status IN ('COMPLETED', 'CANCELED') THEN r.balace_amount ELSE 0 END), 0) AS Difference " + + "FROM " + + "booking_details bd " + + "JOIN " + + "hall_details h ON bd.hall_details_hall_id = h.hall_id " + + "LEFT JOIN users u ON bd.users_user_id = u.user_id " + + "JOIN " + + "payments p ON bd.booking_id = p.booking_details_booking_id " + + "LEFT JOIN refund_response r ON bd.booking_id = r.booking_id " + + "WHERE DATE(bd.booking_date) >= :fromDate " + + "AND DATE(bd.booking_date) <= :toDate " + + "AND bd.booking_status NOT IN ('PENDING')" + + "GROUP BY " + + "bd.hall_details_hall_id", nativeQuery = true) + List getBookingHallDetailsReport(@Param("fromDate") String fromDate, @Param("toDate") String toDate); + + @Query(value = "SELECT \r\n" + + " COALESCE( SUM(\r\n" + + " CASE \r\n" + + " WHEN start_date = CURDATE() THEN 1\r\n" + + " ELSE 0\r\n" + + " END\r\n" + + " ),0) AS currente,\r\n" + + " COALESCE( SUM(\r\n" + + " CASE \r\n" + + " \r\n" + + " WHEN start_date < CURDATE() THEN 1\r\n" + + " ELSE 0\r\n" + + " END\r\n" + + " ), 0) AS past,\r\n" + + " COALESCE( SUM(\r\n" + + " CASE \r\n" + + " \r\n" + + " WHEN start_date > CURDATE() THEN 1\r\n" + + " ELSE 0\r\n" + + " END\r\n" + + " ),0) AS FUTURE\r\n" + + "FROM \r\n" + + " booking_details hall\r\n" + + " where hall_details_hall_id= :hall_id and booking_status='APPROVED'", nativeQuery = true) + List> pieChartCount(int hall_id); + + //@Query(value = "SELECT * FROM booking_details WHERE DATE(booking_date) >= :fromDate AND DATE(booking_date) <= :toDate AND (:bookingStatus IS NULL OR booking_status = :bookingStatus)", nativeQuery = true) + @Query(value = "SELECT bd.booking_id, bd.booking_date, hd.hall_name, us.name, us.mobile_no, " + + "CONCAT(us.doorno, ', ', us.street, ', ', us.area, ', ', us.location, ', ', us.pin_code) AS address, " + + "us.usertype, bd.reason, bd.start_date, bd.end_date, " + + "(bd.deposit_amount + bd.hall_amount + bd.gst) AS amount_paid, bd.booking_status " + + "FROM booking_details bd " + + "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + + "JOIN users us ON bd.users_user_id = us.user_id " + + "WHERE DATE(bd.booking_date) >= :fromDate " + + "AND DATE(bd.booking_date) <= :toDate " + + "AND (:bookingStatus IS NULL OR bd.booking_status = :bookingStatus) ", + nativeQuery = true) + List getAllBookingDetailsWithStatus(@Param("fromDate") String fromDate, + @Param("toDate") String toDate, + @Param("bookingStatus") String bookingStatus); + + @Query(value = "SELECT bd.booking_id, bd.booking_date, hd.hall_name, us.name, us.mobile_no, " + + "CONCAT(us.doorno, ', ', us.street, ', ', us.area, ', ', us.location, ', ', us.pin_code) AS address, " + + "us.usertype, bd.reason, bd.start_date, bd.end_date, " + + "bd.deposit_amount, bd.hall_amount, bd.gst, bd.amount_received, bd.booking_status " + + "FROM booking_details bd " + + "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + + "JOIN users us ON bd.users_user_id = us.user_id " + + "WHERE DATE(bd.booking_date) >= :fromDate " + + "AND DATE(bd.booking_date) <= :toDate " + + "AND (:bookingId IS NULL OR bd.booking_id = :bookingId)", + nativeQuery = true) + List getAllBookingDetailsWithBookingId(@Param("fromDate") String fromDate, + @Param("toDate") String toDate, + @Param("bookingId") Long bookingId); + + @Query(value = "SELECT bd.booking_id, bd.booking_date, hd.hall_name, us.name, us.mobile_no, " + + "CONCAT(us.doorno, ', ', us.street, ', ', us.area, ', ', us.location, ', ', us.pin_code) AS address, " + + "us.usertype, bd.reason, bd.start_date, bd.end_date, " + + "bd.deposit_amount, bd.hall_amount, bd.gst, bd.amount_received, bd.booking_status " + + "FROM booking_details bd " + + "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + + "JOIN users us ON bd.users_user_id = us.user_id " + + "WHERE DATE(bd.booking_date) >= :fromDate " + + "AND DATE(bd.booking_date) <= :toDate " + + "AND (:bookingId IS NULL OR bd.booking_id = :bookingId)" + + "AND (:bookingStatus IS NULL OR bd.booking_status = :bookingStatus)", + nativeQuery = true) + List getAllBookingDetailsWithBookingIdwithbookingStatus(@Param("fromDate") String fromDate, + @Param("toDate") String toDate, + @Param("bookingId") Long bookingId, @Param("bookingStatus") String bookingStatus); + + //@Query(value = "SELECT * FROM booking_details WHERE DATE(booking_date) >= :fromDate AND DATE(booking_date) <= :toDate", nativeQuery = true) + @Query(value = "SELECT bd.booking_id, bd.booking_date, hd.hall_name, us.name, us.mobile_no, " + + "CONCAT(us.doorno, ', ', us.street, ', ', us.area, ', ', us.location, ', ', us.pin_code) AS address, " + + "us.usertype, bd.reason, bd.start_date, bd.end_date, " + + "(bd.deposit_amount + bd.hall_amount + bd.gst) AS amount_paid, bd.booking_status " + + "FROM booking_details bd " + + "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + + "JOIN users us ON bd.users_user_id = us.user_id " + + "WHERE DATE(bd.booking_date) >= :fromDate " + + "AND DATE(bd.booking_date) <= :toDate ", + nativeQuery = true) + List getAllBookingDetails(@Param("fromDate") String fromDate, @Param("toDate") String toDate); + // @Query(value = "SELECT bd.booking_id, bd.booking_date, hd.hall_name, us.name, us.usertype, p.transaction_id, p.payment_type, p.amount_received, bd.reason, bd.start_date, bd.end_date, p.payment_status " + // "FROM payments p " + // "JOIN booking_details bd ON p.booking_details_booking_id =bd.booking_id " + @@ -236,801 +241,805 @@ List findPastEventsByHallId(@Param("hallId") Integer hallId); // List getAllPaymentsDetails(@Param("fromDate") String fromDate, // @Param("toDate") String toDate, // @Param("paymentStatus") String paymentStatus); - - @Query(value = "SELECT SUM(CASE WHEN bd.booking_status = 'APPROVED' THEN 1 ELSE 0 END) AS approved_booking_count,\r\n" - + "SUM(CASE WHEN bd.booking_status = 'REJECTED' THEN 1 ELSE 0 END) AS rejected_booking_count,\r\n" - + "SUM(CASE WHEN bd.refund_status = 'WAITING' THEN 1 ELSE 0 END) AS waiting_settlement_count,\r\n" - + "SUM(CASE WHEN bd.refund_status = 'APPROVED' THEN 1 ELSE 0 END) AS approved_settlement_count,\r\n" - + "SUM(CASE WHEN bd.refund_status = 'REJECTED' THEN 1 ELSE 0 END) AS reject_settlement_count\r\n" - + "FROM booking_details bd " - + "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " - + "WHERE hd.zone = :zone", nativeQuery = true) - List> toatlBookingCount(String zone); - - @Query(value = " SELECT SUM(CASE WHEN booking_status = 'APPROVED' THEN 1 ELSE 0 END) AS approved_count,\r\n" - + " SUM(CASE WHEN bd.booking_status = 'REJECTED' THEN 1 ELSE 0 END) AS rejected_count,\r\n" - + " SUM(CASE WHEN bd.booking_status = 'PENDING' THEN 1 ELSE 0 END) AS pending_count,\r\n" - + " SUM(CASE WHEN bd.booking_status = 'CANCELED' THEN 1 ELSE 0 END) AS CANCELED,\r\n" - + " SUM(CASE WHEN bd.booking_status = 'PAYMENT_FAILURE' THEN 1 ELSE 0 END) AS PAYMENT_FAILURE,\r\n" - + " SUM(CASE WHEN bd.booking_status = 'GCC_BLOCKED' THEN 1 ELSE 0 END) AS GCC_BLOCKED\r\n" - + "FROM booking_details bd " - + "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " - + "WHERE hd.zone = :zone",nativeQuery = true) - List> getCount(String zone); - - + + @Query(value = "SELECT SUM(CASE WHEN bd.booking_status = 'APPROVED' THEN 1 ELSE 0 END) AS approved_booking_count,\r\n" + + "SUM(CASE WHEN bd.booking_status = 'REJECTED' THEN 1 ELSE 0 END) AS rejected_booking_count,\r\n" + + "SUM(CASE WHEN bd.refund_status = 'WAITING' THEN 1 ELSE 0 END) AS waiting_settlement_count,\r\n" + + "SUM(CASE WHEN bd.refund_status = 'APPROVED' THEN 1 ELSE 0 END) AS approved_settlement_count,\r\n" + + "SUM(CASE WHEN bd.refund_status = 'REJECTED' THEN 1 ELSE 0 END) AS reject_settlement_count\r\n" + + "FROM booking_details bd " + + "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + + "WHERE hd.zone = :zone", nativeQuery = true) + List> toatlBookingCount(String zone); + + @Query(value = " SELECT SUM(CASE WHEN booking_status = 'APPROVED' THEN 1 ELSE 0 END) AS approved_count,\r\n" + + " SUM(CASE WHEN bd.booking_status = 'REJECTED' THEN 1 ELSE 0 END) AS rejected_count,\r\n" + + " SUM(CASE WHEN bd.booking_status = 'PENDING' THEN 1 ELSE 0 END) AS pending_count,\r\n" + + " SUM(CASE WHEN bd.booking_status = 'CANCELED' THEN 1 ELSE 0 END) AS CANCELED,\r\n" + + " SUM(CASE WHEN bd.booking_status = 'PAYMENT_FAILURE' THEN 1 ELSE 0 END) AS PAYMENT_FAILURE,\r\n" + + " SUM(CASE WHEN bd.booking_status = 'GCC_BLOCKED' THEN 1 ELSE 0 END) AS GCC_BLOCKED\r\n" + + "FROM booking_details bd " + + "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + + "WHERE hd.zone = :zone", nativeQuery = true) + List> getCount(String zone); + + @Query(value = "SELECT CONCAT(YEAR(bd.start_date), '-', LPAD(MONTH(bd.start_date), 2, '0')) AS months, SUM(CASE WHEN booking_status = 'APPROVED' THEN 1 ELSE 0 END) AS approved_count,\r\n" - + " SUM(CASE WHEN bd.booking_status = 'REJECTED' THEN 1 ELSE 0 END) AS rejected_count,\r\n" - + " SUM(CASE WHEN bd.booking_status = 'PENDING' THEN 1 ELSE 0 END) AS pending_count\r\n" - + "FROM booking_details bd JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id \r\n" - + "WHERE bd.start_date >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH)\r\n" - + " AND bd.start_date <= DATE_ADD(CURDATE(), INTERVAL 6 MONTH) AND hd.zone = :zone \r\n" - + " group by months order by months ASC",nativeQuery = true) + + " SUM(CASE WHEN bd.booking_status = 'REJECTED' THEN 1 ELSE 0 END) AS rejected_count,\r\n" + + " SUM(CASE WHEN bd.booking_status = 'PENDING' THEN 1 ELSE 0 END) AS pending_count\r\n" + + "FROM booking_details bd JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id \r\n" + + "WHERE bd.start_date >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH)\r\n" + + " AND bd.start_date <= DATE_ADD(CURDATE(), INTERVAL 6 MONTH) AND hd.zone = :zone \r\n" + + " group by months order by months ASC", nativeQuery = true) List> getmounthcount(String zone); - - + + @Query(value = "SELECT CONCAT(YEAR(bd.start_date), '-', LPAD(MONTH(bd.start_date), 2, '0')) AS months, SUM(CASE WHEN booking_status = 'APPROVED' THEN 1 ELSE 0 END) AS approved_count,\r\n" - + " SUM(CASE WHEN bd.booking_status = 'REJECTED' THEN 1 ELSE 0 END) AS rejected_count,\r\n" - + " SUM(CASE WHEN bd.booking_status = 'PENDING' THEN 1 ELSE 0 END) AS pending_count\r\n" - + "FROM booking_details bd JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id \r\n" - + "WHERE bd.start_date >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH)\r\n" - + " AND bd.start_date <= DATE_ADD(CURDATE(), INTERVAL 6 MONTH) \r\n" - + "AND (:zone = 'all zones' OR hd.zone = :zone)\r\n " - + " group by months order by months ASC",nativeQuery = true) - List> getAllAdminmonthcount(@Param("zone") String zone); - - - - @Query(value = " SELECT SUM(CASE WHEN booking_status = 'APPROVED' THEN 1 ELSE 0 END) AS approved_count,\r\n" - + " SUM(CASE WHEN bd.booking_status = 'REJECTED' THEN 1 ELSE 0 END) AS rejected_count,\r\n" - + " SUM(CASE WHEN bd.booking_status = 'PENDING' THEN 1 ELSE 0 END) AS pending_count,\r\n" - + " SUM(CASE WHEN bd.booking_status = 'CANCELED' THEN 1 ELSE 0 END) AS CANCELED,\r\n" - + " SUM(CASE WHEN bd.booking_status = 'PAYMENT_FAILURE' THEN 1 ELSE 0 END) AS PAYMENT_FAILURE,\r\n" - + " SUM(CASE WHEN bd.booking_status = 'GCC_BLOCKED' THEN 1 ELSE 0 END) AS GCC_BLOCKED\r\n" - + "FROM booking_details bd " - + "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " - + "WHERE (:zone = 'all zones' OR hd.zone = :zone)",nativeQuery = true) + + " SUM(CASE WHEN bd.booking_status = 'REJECTED' THEN 1 ELSE 0 END) AS rejected_count,\r\n" + + " SUM(CASE WHEN bd.booking_status = 'PENDING' THEN 1 ELSE 0 END) AS pending_count\r\n" + + "FROM booking_details bd JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id \r\n" + + "WHERE bd.start_date >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH)\r\n" + + " AND bd.start_date <= DATE_ADD(CURDATE(), INTERVAL 6 MONTH) \r\n" + + "AND (:zone = 'all zones' OR hd.zone = :zone)\r\n " + + " group by months order by months ASC", nativeQuery = true) + List> getAllAdminmonthcount(@Param("zone") String zone); + + + @Query(value = " SELECT SUM(CASE WHEN booking_status = 'APPROVED' THEN 1 ELSE 0 END) AS approved_count,\r\n" + + " SUM(CASE WHEN bd.booking_status = 'REJECTED' THEN 1 ELSE 0 END) AS rejected_count,\r\n" + + " SUM(CASE WHEN bd.booking_status = 'PENDING' THEN 1 ELSE 0 END) AS pending_count,\r\n" + + " SUM(CASE WHEN bd.booking_status = 'CANCELED' THEN 1 ELSE 0 END) AS CANCELED,\r\n" + + " SUM(CASE WHEN bd.booking_status = 'PAYMENT_FAILURE' THEN 1 ELSE 0 END) AS PAYMENT_FAILURE,\r\n" + + " SUM(CASE WHEN bd.booking_status = 'GCC_BLOCKED' THEN 1 ELSE 0 END) AS GCC_BLOCKED\r\n" + + "FROM booking_details bd " + + "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + + "WHERE (:zone = 'all zones' OR hd.zone = :zone)", nativeQuery = true) List> getAdmincount(@Param("zone") String zone); - - @Query(value = "SELECT CONCAT(YEAR(bd.start_date), '-', LPAD(MONTH(bd.start_date), 2, '0')) AS months, SUM(CASE WHEN booking_status = 'APPROVED' THEN 1 ELSE 0 END) AS approved_count,\r\n" - + " SUM(CASE WHEN bd.booking_status = 'REJECTED' THEN 1 ELSE 0 END) AS rejected_count,\r\n" - + " SUM(CASE WHEN bd.booking_status = 'COMPLETED' THEN 1 ELSE 0 END) AS completed_count\r\n" - + "FROM booking_details bd JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id \r\n" - + "WHERE bd.start_date >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH)\r\n" - + " AND bd.start_date <= DATE_ADD(CURDATE(), INTERVAL 6 MONTH) AND hd.hall_id=:hall_id \r\n" - + " group by months order by months ASC",nativeQuery = true) - List> getCartakermounthcount(int hall_id); - - - @Query(value = " SELECT SUM(CASE WHEN booking_status = 'APPROVED' THEN 1 ELSE 0 END) AS approved_count,\r\n" - + " SUM(CASE WHEN bd.booking_status = 'REJECTED' THEN 1 ELSE 0 END) AS rejected_count,\r\n" - + " SUM(CASE WHEN bd.booking_status = 'COMPLETED' THEN 1 ELSE 0 END) AS completed_count,\r\n" - + " SUM(CASE WHEN bd.booking_status = 'CANCELED' THEN 1 ELSE 0 END) AS CANCELED,\r\n" - + " SUM(CASE WHEN bd.booking_status = 'PAYMENT_FAILURE' THEN 1 ELSE 0 END) AS PAYMENT_FAILURE,\r\n" - + " SUM(CASE WHEN bd.booking_status = 'GCC_BLOCKED' THEN 1 ELSE 0 END) AS GCC_BLOCKED\r\n" - + "FROM booking_details bd " - + "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id where hd.hall_id=:hall_id",nativeQuery = true) - List> getcartakecount(int hall_id); - - @Query(value ="SELECT \r\n" - + " bd.*, \r\n" - + " CASE \r\n" - + " WHEN bd.start_date < CURDATE() THEN 'Past'\r\n" - + " WHEN bd.start_date = CURDATE() THEN 'Current'\r\n" - + " WHEN bd.reason IN ('State Govt Event','Central Govt Event','Commericial & Others') AND bd.booking_status='APPROVED' THEN 'noaction'" - + " WHEN bd.booking_status = 'WAITING_FOR_NOC' THEN 'waitingfornoc'\r\n" - + " WHEN bd.schedule_count = 0 AND bd.start_date > CURDATE() THEN 'Reschedule'\r\n" - + " ELSE 'Future' \r\n" - + " END AS event_category,\r\n" - + " users.*, \r\n" - + " hd.*, \r\n" - + " cd.*, \r\n" - + " pd.* \r\n" - + "FROM booking_details bd \r\n" - + "INNER JOIN users users ON bd.users_user_id = users.user_id \r\n" - + "INNER JOIN hall_details hd ON hd.hall_id = bd.hall_details_hall_id \r\n" - + "LEFT JOIN counter_details cd ON cd.counter_id = bd.counterdetails_counter_id\r\n" - + "LEFT JOIN payments pd ON bd.booking_id = pd.booking_details_booking_id \r\n" - + "WHERE bd.users_user_id = :userId and booking_status IN ('GCC_BLOCKED', 'APPROVED','CANCELED','REJECTED','COMPLETED','WAITING_FOR_NOC','WAITING_FOR_NOC_APPROVAL') \r\n" - + "ORDER BY bd.start_date DESC;\r\n" - + "", nativeQuery = true) - List> getAllBookingEventsByUserId(Integer userId); -//counter - @Query(value = "SELECT bd.*, " + - "hd.zone AS hall_zone, " + - "hd.division AS hall_division, " + - "users.mobile_no AS mobile_no, " + - "CASE " + - "WHEN bd.start_date < CURDATE() THEN 'Past' " + - "WHEN bd.start_date = CURDATE() THEN 'Current' " + - "ELSE 'Future' " + - "END AS event_category " + - "FROM booking_details bd " + - "INNER JOIN users users on bd.users_user_id = users.user_id " + - "INNER JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + - "WHERE bd.booking_type = 'OFFLINE'", - nativeQuery = true) - List> findAllByBookingType(); - - - @Query(value="select bdud.* from booking_details bdud inner Join counter_refund_list crl on bdud.counterdetails_counter_id = crl.counterdetails_counter_id where crl.counterdetails_counter_id = :counterId", nativeQuery = true) - List getCounterDetailsbycounterId(int counterId); - - @Query(value="select *from booking_details where counterdetails_counter_id = :counterId", nativeQuery = true) - List findByCounterId(int counterId); - - @Query("SELECT b FROM BookingDetails b LEFT JOIN FETCH b.bookingHistories WHERE b.bookingId = :bookingId") + + @Query(value = "SELECT CONCAT(YEAR(bd.start_date), '-', LPAD(MONTH(bd.start_date), 2, '0')) AS months, SUM(CASE WHEN booking_status = 'APPROVED' THEN 1 ELSE 0 END) AS approved_count,\r\n" + + " SUM(CASE WHEN bd.booking_status = 'REJECTED' THEN 1 ELSE 0 END) AS rejected_count,\r\n" + + " SUM(CASE WHEN bd.booking_status = 'COMPLETED' THEN 1 ELSE 0 END) AS completed_count\r\n" + + "FROM booking_details bd JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id \r\n" + + "WHERE bd.start_date >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH)\r\n" + + " AND bd.start_date <= DATE_ADD(CURDATE(), INTERVAL 6 MONTH) AND hd.hall_id=:hall_id \r\n" + + " group by months order by months ASC", nativeQuery = true) + List> getCartakermounthcount(int hall_id); + + + @Query(value = " SELECT SUM(CASE WHEN booking_status = 'APPROVED' THEN 1 ELSE 0 END) AS approved_count,\r\n" + + " SUM(CASE WHEN bd.booking_status = 'REJECTED' THEN 1 ELSE 0 END) AS rejected_count,\r\n" + + " SUM(CASE WHEN bd.booking_status = 'COMPLETED' THEN 1 ELSE 0 END) AS completed_count,\r\n" + + " SUM(CASE WHEN bd.booking_status = 'CANCELED' THEN 1 ELSE 0 END) AS CANCELED,\r\n" + + " SUM(CASE WHEN bd.booking_status = 'PAYMENT_FAILURE' THEN 1 ELSE 0 END) AS PAYMENT_FAILURE,\r\n" + + " SUM(CASE WHEN bd.booking_status = 'GCC_BLOCKED' THEN 1 ELSE 0 END) AS GCC_BLOCKED\r\n" + + "FROM booking_details bd " + + "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id where hd.hall_id=:hall_id", nativeQuery = true) + List> getcartakecount(int hall_id); + + @Query(value = "SELECT \r\n" + + " bd.*, \r\n" + + " CASE \r\n" + + " WHEN bd.start_date < CURDATE() THEN 'Past'\r\n" + + " WHEN bd.start_date = CURDATE() THEN 'Current'\r\n" + + " WHEN bd.booking_status = 'WAITING_FOR_NOC' THEN 'waitingfornoc'\r\n" + + " WHEN bd.schedule_count = 0 AND bd.start_date > CURDATE() THEN 'Reschedule'\r\n" + + " WHEN bd.reason IN ('State Govt Event','Central Govt Event','Commericial & Others') AND bd.booking_status='APPROVED' THEN 'noaction'" + + " ELSE 'Future' \r\n" + + " END AS event_category,\r\n" + + " users.*, \r\n" + + " hd.*, \r\n" + + " cd.*, \r\n" + + " pd.* \r\n" + + "FROM booking_details bd \r\n" + + "INNER JOIN users users ON bd.users_user_id = users.user_id \r\n" + + "INNER JOIN hall_details hd ON hd.hall_id = bd.hall_details_hall_id \r\n" + + "LEFT JOIN counter_details cd ON cd.counter_id = bd.counterdetails_counter_id\r\n" + + "LEFT JOIN payments pd ON bd.booking_id = pd.booking_details_booking_id \r\n" + + "WHERE bd.users_user_id = :userId and booking_status IN ('GCC_BLOCKED', 'APPROVED','CANCELED','REJECTED','COMPLETED','WAITING_FOR_NOC','WAITING_FOR_NOC_APPROVAL') \r\n" + + "ORDER BY bd.start_date DESC;\r\n" + + "", nativeQuery = true) + List> getAllBookingEventsByUserId(Integer userId); + + //counter + @Query(value = "SELECT bd.*, " + + "hd.zone AS hall_zone, " + + "hd.division AS hall_division, " + + "users.mobile_no AS mobile_no, " + + "CASE " + + "WHEN bd.start_date < CURDATE() THEN 'Past' " + + "WHEN bd.start_date = CURDATE() THEN 'Current' " + + "ELSE 'Future' " + + "END AS event_category " + + "FROM booking_details bd " + + "INNER JOIN users users on bd.users_user_id = users.user_id " + + "INNER JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + + "WHERE bd.booking_type = 'OFFLINE'", + nativeQuery = true) + List> findAllByBookingType(); + + + @Query(value = "select bdud.* from booking_details bdud inner Join counter_refund_list crl on bdud.counterdetails_counter_id = crl.counterdetails_counter_id where crl.counterdetails_counter_id = :counterId", nativeQuery = true) + List getCounterDetailsbycounterId(int counterId); + + @Query(value = "select *from booking_details where counterdetails_counter_id = :counterId", nativeQuery = true) + List findByCounterId(int counterId); + + @Query("SELECT b FROM BookingDetails b LEFT JOIN FETCH b.bookingHistories WHERE b.bookingId = :bookingId") Optional findByIdWithHistories(@Param("bookingId") int bookingId); - @Query("SELECT b FROM BookingDetails b JOIN FETCH b.settlement s WHERE b.refundStatus = 'APPROVED'") - List findAllWithApprovedRefundStatus(); - @Query("SELECT b FROM BookingDetails b JOIN FETCH b.settlement s WHERE b.refundStatus = 'INITIATED'") - List findByBookingDetailsRefundStatus(); - - @Query("SELECT b FROM BookingDetails b JOIN FETCH b.settlement s WHERE b.refundStatus = 'COMPLETED' AND b.bookingStatus='COMPLETED'") - List findAllwithCompletedRefundStatus(); - - @Query("SELECT b FROM BookingDetails b JOIN FETCH b.settlement s WHERE b.refundStatus = 'WAITING' and b.hallDetails.zone=:zone") - List findSettlementPendingByZone(String zone); - - @Query("SELECT b FROM BookingDetails b JOIN FETCH b.settlement s WHERE b.refundStatus = 'APPROVED' and b.hallDetails.zone=:zone") - List findSettlementApprovedByZone(String zone); - - @Query("SELECT b FROM BookingDetails b JOIN FETCH b.settlement s WHERE b.refundStatus = 'REJECTED' and b.hallDetails.zone=:zone") - List findSettlementRejectedByZone(String zone); - - @Query("SELECT b FROM BookingDetails b WHERE b.refundStatus = 'WAITING' AND b.bookingStatus = 'CANCELED' AND b.hallDetails.zone = :zone") - List findCancelledListByZone(@Param("zone") String zone); - - @Query("SELECT b FROM BookingDetails b WHERE b.refundStatus = 'APPROVED' AND b.bookingStatus = 'CANCELED' AND b.hallDetails.zone = :zone") - List findapprovedCancelledListByZone(String zone); - - @Query("SELECT b FROM BookingDetails b WHERE b.refundStatus = 'WAITING' AND b.bookingStatus IN ('GCC_BLOCKED', 'REJECTED') AND b.hallDetails.zone = :zone") - List findRejectedListByZone(@Param("zone") String zone); - - @Query("SELECT b FROM BookingDetails b WHERE b.refundStatus = 'APPROVED' AND b.bookingStatus IN ('GCC_BLOCKED', 'REJECTED') AND b.hallDetails.zone = :zone") - List findapprovedRejectedListByZone(@Param("zone") String zone); - - @Query("SELECT b FROM BookingDetails b WHERE b.refundStatus = 'APPROVED' AND b.bookingStatus = 'CANCELED'") - List findCancelledList(); - - - @Query(value = "SELECT * FROM booking_details WHERE refund_status = 'APPROVED' AND booking_status IN ('GCC_BLOCKED', 'REJECTED')", nativeQuery = true) - List findRejectedList(); - @Query(value = "SELECT * FROM booking_details WHERE refund_status = 'INITIATED' AND booking_status = 'CANCELED'", nativeQuery = true) - List findInitiatedCancelledList(); - @Query(value = "SELECT * FROM booking_details WHERE refund_status = 'INITIATED' AND booking_status IN ('GCC_BLOCKED', 'REJECTED')", nativeQuery = true) - List findInitiatedRejectedList(); - - @Query(value = "SELECT * FROM booking_details WHERE refund_status IN ('COMPLETED','CLOSED') AND booking_status = 'COMPLETED'", nativeQuery = true) - List findSettlementCompletedList(); - @Query(value = "SELECT * FROM booking_details WHERE refund_status = 'COMPLETED' AND booking_status = 'CANCELED'", nativeQuery = true) - List findCancelledCompletedList(); - @Query(value = "SELECT * FROM booking_details WHERE refund_status = 'COMPLETED' AND booking_status IN ('GCC_BLOCKED', 'REJECTED')", nativeQuery = true) - List findRejectedSettlementCompletedList(); - - //officer reports - @Query(value ="SELECT bd.*, hd.hall_name, us.name, us.usertype "+ - "FROM booking_details bd "+ - "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id "+ - "JOIN users us ON bd.users_user_id = us.user_id "+ - "WHERE DATE(bd.booking_date) >= :fromDate "+ - "AND DATE(bd.booking_date) <= :toDate " + - "AND hd.zone = :zone ",nativeQuery=true) - List getAllBookingDetailsByZone(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("zone") String zone); - - @Query(value ="SELECT bd.*, hd.hall_name, us.name, us.usertype " + - "FROM booking_details bd " + - "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id "+ - "JOIN users us ON bd.users_user_id = us.user_id " + - "WHERE DATE(bd.booking_date) >= :fromDate " + - "AND DATE(bd.booking_date) <= :toDate " + - "AND hd.zone = :zone " + - "AND (:bookingStatus IS NULL OR bd.booking_status = :bookingStatus)",nativeQuery=true) - List getAllBookingDetailsByZoneWithStatus(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("zone") String zone,@Param("bookingStatus") String bookingStatus); - - @Query(value = "SELECT " + - "h.hall_name AS HallName, " + - "h.zone AS Zone, " + - "h.division AS Division, " + - "CONCAT(h.door_no,',',h.street, ', ', h.area, ', ', h.city, ', ', h.pin_code) AS Address, " + - "COUNT(*) AS HallTotalBookings, " + - "SUM(p.amount_received) AS AmountReceived, " + - "COALESCE(SUM(r.amount_refunded), 0) AS AmountRefund, " + //Use COALESCE to handle NULL values - "(SUM(p.amount_received) - COALESCE(SUM(r.amount_refunded), 0)) AS Difference " + // Calculate the difference - "FROM " + - "booking_details bd " + - "JOIN " + - "hall_details h ON bd.hall_details_hall_id = h.hall_id " + - "JOIN " + - "payments p ON bd.booking_id = p.booking_details_booking_id " + - "LEFT JOIN " + - "refund_transaction r ON p.transaction_id = r.transaction_id " + - "WHERE DATE(bd.booking_date) >= :fromDate "+ - "AND DATE(bd.booking_date) <= :toDate " + - "AND h.zone = :zone " + - "GROUP BY " + - "bd.hall_details_hall_id", nativeQuery = true) - List getBookingHallDetailsReportByZone(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("zone") String zone); - - @Query(value ="SELECT bd.*, hd.hall_name, us.name, us.usertype " + - "FROM booking_details bd " + - "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + - "LEFT JOIN users us ON bd.users_user_id = us.user_id " + - "LEFT JOIN settlement st ON bd.booking_id=st.booking_details_booking_id " + - "WHERE DATE(bd.booking_date) >= :fromDate " + - "AND DATE(bd.booking_date) <= :toDate " + - "AND bd.booking_status NOT IN ('PENDING')"+ - "AND hd.zone = :zone ",nativeQuery=true) - List getAllBookingsettlementDetailsByZone(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("zone") String zone); - - @Query(value ="SELECT bd.*, hd.hall_name, us.name, us.usertype " + - "FROM booking_details bd " + - "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + - "LEFT JOIN users us ON bd.users_user_id = us.user_id " + - "LEFT JOIN settlement st ON bd.booking_id=st.booking_details_booking_id " + - "WHERE DATE(bd.booking_date) >= :fromDate " + - "AND DATE(bd.booking_date) <= :toDate " + - "AND bd.booking_status NOT IN ('PENDING')"+ - "AND hd.zone = :zone " + - "AND (:refundStatus IS NULL OR bd.refund_status = :refundStatus) ",nativeQuery=true) - List getAllBookingsettlementDetailsByZoneWithStatus(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("zone") String zone,@Param("refundStatus") String refundStatus); - - -@Query(value = "SELECT " + - "h.hall_name AS HallName, " + - "h.hall_Incharge_name AS InchargeName, " + - "h.hall_Incharge_no AS hallInchargeMobno, " + - "CONCAT(h.zone, '/', h.division) AS ZoneDivision, " + // Concatenate zone and division - "COUNT(*) AS HallTotalBookings, " + - "SUM(p.amount_received) AS AmountReceived, " + - "COALESCE(SUM(r.amount - r.balace_amount), 0) AS AmountRefund, " + - "COALESCE(SUM(CASE WHEN bd.booking_status IN ('COMPLETED', 'CANCELED') THEN r.balace_amount ELSE 0 END), 0) AS Difference " + - "FROM " + - "booking_details bd " + - "JOIN " + - "hall_details h ON bd.hall_details_hall_id = h.hall_id " + - "LEFT JOIN users u ON bd.users_user_id = u.user_id "+ - "JOIN " + - "payments p ON bd.booking_id = p.booking_details_booking_id " + - "LEFT JOIN refund_response r ON bd.booking_id = r.booking_id " + - "WHERE DATE(bd.booking_date) >= :fromDate " + - "AND DATE(bd.booking_date) <= :toDate " + - "AND bd.booking_status NOT IN ('PENDING')"+ - "AND h.zone = :zone " + - "AND bd.hall_details_hall_id = :hall_id " + - "GROUP BY " + - "bd.hall_details_hall_id", nativeQuery = true) - List getBookingHallDetailsReportByZone1(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("zone") String zone,@Param("hall_id") Integer hallId); - - List findByHallDetailsAndBookingStatus(HallDetails hallDetails, BookingStatus gccBlocked); - - @Query(value = "SELECT COUNT(*) FROM booking_details WHERE hall_details_hall_id = :hallId AND start_date BETWEEN :startDate AND :endDate AND booking_status='GCC_BLOCKED'", nativeQuery = true) - int countByHallIdAndBookingDateBetween( - @Param("hallId") int hallId, - @Param("startDate") LocalDate startDate, - @Param("endDate") LocalDate endDate); - - @Query(value = "SELECT * FROM booking_details WHERE booking_id=:bookingId", nativeQuery = true) - List findBookingDetailsByBookingId(@Param("bookingId") Long bookingId); - - @Query(value = "SELECT booking_id FROM booking_details WHERE hall_details_hall_id = :hallId AND start_date BETWEEN :startDate AND :endDate AND booking_status='GCC_BLOCKED'", nativeQuery = true) - List findBookingIdsByHallIdAndBookingDateBetween(@Param("hallId") int hallId, @Param("startDate") LocalDate startDate, @Param("endDate") LocalDate endDate); - - @Query(value ="SELECT bd.*, hd.hall_name, us.name, us.usertype " + - "FROM booking_details bd " + - "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + - "LEFT JOIN users us ON bd.users_user_id = us.user_id " + - "LEFT JOIN settlement st ON bd.booking_id=st.booking_details_booking_id " + - "WHERE DATE(bd.booking_date) >= :fromDate " + - "AND DATE(bd.booking_date) <= :toDate " + - "AND bd.booking_status NOT IN ('PENDING')"+ - "AND (:refundStatus IS NULL OR bd.refund_status = :refundStatus) ",nativeQuery=true) - List getAllBookingsettlementDetailsWithStatus(@Param("fromDate") String fromDate, @Param("toDate") String toDate,@Param("refundStatus") String refundStatus); - - @Query(value ="SELECT bd.*, hd.hall_name, us.name, us.usertype " + - "FROM booking_details bd " + - "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + - "LEFT JOIN users us ON bd.users_user_id = us.user_id " + - "LEFT JOIN settlement st ON bd.booking_id=st.booking_details_booking_id " + - "WHERE DATE(bd.booking_date) >= :fromDate " + - "AND bd.booking_status NOT IN ('PENDING')"+ - "AND DATE(bd.booking_date) <= :toDate ",nativeQuery=true) - List getAllBookingsettlementDetails(@Param("fromDate") String fromDate, @Param("toDate") String toDate); + @Query("SELECT b FROM BookingDetails b JOIN FETCH b.settlement s WHERE b.refundStatus = 'APPROVED'") + List findAllWithApprovedRefundStatus(); + + @Query("SELECT b FROM BookingDetails b JOIN FETCH b.settlement s WHERE b.refundStatus = 'INITIATED'") + List findByBookingDetailsRefundStatus(); + + @Query("SELECT b FROM BookingDetails b JOIN FETCH b.settlement s WHERE b.refundStatus = 'COMPLETED' AND b.bookingStatus='COMPLETED'") + List findAllwithCompletedRefundStatus(); + + @Query("SELECT b FROM BookingDetails b JOIN FETCH b.settlement s WHERE b.refundStatus = 'WAITING' and b.hallDetails.zone=:zone") + List findSettlementPendingByZone(String zone); + + @Query("SELECT b FROM BookingDetails b JOIN FETCH b.settlement s WHERE b.refundStatus = 'APPROVED' and b.hallDetails.zone=:zone") + List findSettlementApprovedByZone(String zone); + + @Query("SELECT b FROM BookingDetails b JOIN FETCH b.settlement s WHERE b.refundStatus = 'REJECTED' and b.hallDetails.zone=:zone") + List findSettlementRejectedByZone(String zone); + + @Query("SELECT b FROM BookingDetails b JOIN FETCH b.settlement s WHERE b.refundStatus = 'REJECTED'") + List findAllSettlementRejected(); + + + @Query("SELECT b FROM BookingDetails b WHERE b.refundStatus = 'WAITING' AND b.bookingStatus = 'CANCELED' AND b.hallDetails.zone = :zone") + List findCancelledListByZone(@Param("zone") String zone); + + @Query("SELECT b FROM BookingDetails b WHERE b.refundStatus = 'APPROVED' AND b.bookingStatus = 'CANCELED' AND b.hallDetails.zone = :zone") + List findapprovedCancelledListByZone(String zone); + + @Query("SELECT b FROM BookingDetails b WHERE b.refundStatus = 'WAITING' AND b.bookingStatus IN ('GCC_BLOCKED', 'REJECTED') AND b.hallDetails.zone = :zone") + List findRejectedListByZone(@Param("zone") String zone); + + @Query("SELECT b FROM BookingDetails b WHERE b.refundStatus = 'APPROVED' AND b.bookingStatus IN ('GCC_BLOCKED', 'REJECTED') AND b.hallDetails.zone = :zone") + List findapprovedRejectedListByZone(@Param("zone") String zone); + + @Query("SELECT b FROM BookingDetails b WHERE b.refundStatus = 'APPROVED' AND b.bookingStatus = 'CANCELED'") + List findCancelledList(); + + + @Query(value = "SELECT * FROM booking_details WHERE refund_status = 'APPROVED' AND booking_status IN ('GCC_BLOCKED', 'REJECTED')", nativeQuery = true) + List findRejectedList(); + + @Query(value = "SELECT * FROM booking_details WHERE refund_status = 'INITIATED' AND booking_status = 'CANCELED'", nativeQuery = true) + List findInitiatedCancelledList(); + + @Query(value = "SELECT * FROM booking_details WHERE refund_status = 'INITIATED' AND booking_status IN ('GCC_BLOCKED', 'REJECTED')", nativeQuery = true) + List findInitiatedRejectedList(); + + @Query(value = "SELECT * FROM booking_details WHERE refund_status IN ('COMPLETED','CLOSED') AND booking_status = 'COMPLETED'", nativeQuery = true) + List findSettlementCompletedList(); + + @Query(value = "SELECT * FROM booking_details WHERE refund_status = 'COMPLETED' AND booking_status = 'CANCELED'", nativeQuery = true) + List findCancelledCompletedList(); + + @Query(value = "SELECT * FROM booking_details WHERE refund_status = 'COMPLETED' AND booking_status IN ('GCC_BLOCKED', 'REJECTED')", nativeQuery = true) + List findRejectedSettlementCompletedList(); + + //officer reports + @Query(value = "SELECT bd.*, hd.hall_name, us.name, us.usertype " + + "FROM booking_details bd " + + "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + + "JOIN users us ON bd.users_user_id = us.user_id " + + "WHERE DATE(bd.booking_date) >= :fromDate " + + "AND DATE(bd.booking_date) <= :toDate " + + "AND hd.zone = :zone ", nativeQuery = true) + List getAllBookingDetailsByZone(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("zone") String zone); + + @Query(value = "SELECT bd.*, hd.hall_name, us.name, us.usertype " + + "FROM booking_details bd " + + "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + + "JOIN users us ON bd.users_user_id = us.user_id " + + "WHERE DATE(bd.booking_date) >= :fromDate " + + "AND DATE(bd.booking_date) <= :toDate " + + "AND hd.zone = :zone " + + "AND (:bookingStatus IS NULL OR bd.booking_status = :bookingStatus)", nativeQuery = true) + List getAllBookingDetailsByZoneWithStatus(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("zone") String zone, @Param("bookingStatus") String bookingStatus); + + @Query(value = "SELECT " + + "h.hall_name AS HallName, " + + "h.zone AS Zone, " + + "h.division AS Division, " + + "CONCAT(h.door_no,',',h.street, ', ', h.area, ', ', h.city, ', ', h.pin_code) AS Address, " + + "COUNT(*) AS HallTotalBookings, " + + "SUM(p.amount_received) AS AmountReceived, " + + "COALESCE(SUM(r.amount_refunded), 0) AS AmountRefund, " + //Use COALESCE to handle NULL values + "(SUM(p.amount_received) - COALESCE(SUM(r.amount_refunded), 0)) AS Difference " + // Calculate the difference + "FROM " + + "booking_details bd " + + "JOIN " + + "hall_details h ON bd.hall_details_hall_id = h.hall_id " + + "JOIN " + + "payments p ON bd.booking_id = p.booking_details_booking_id " + + "LEFT JOIN " + + "refund_transaction r ON p.transaction_id = r.transaction_id " + + "WHERE DATE(bd.booking_date) >= :fromDate " + + "AND DATE(bd.booking_date) <= :toDate " + + "AND h.zone = :zone " + + "GROUP BY " + + "bd.hall_details_hall_id", nativeQuery = true) + List getBookingHallDetailsReportByZone(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("zone") String zone); + + @Query(value = "SELECT bd.*, hd.hall_name, us.name, us.usertype " + + "FROM booking_details bd " + + "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + + "LEFT JOIN users us ON bd.users_user_id = us.user_id " + + "LEFT JOIN settlement st ON bd.booking_id=st.booking_details_booking_id " + + "WHERE DATE(bd.booking_date) >= :fromDate " + + "AND DATE(bd.booking_date) <= :toDate " + + "AND bd.booking_status NOT IN ('PENDING')" + + "AND hd.zone = :zone ", nativeQuery = true) + List getAllBookingsettlementDetailsByZone(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("zone") String zone); + + @Query(value = "SELECT bd.*, hd.hall_name, us.name, us.usertype " + + "FROM booking_details bd " + + "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + + "LEFT JOIN users us ON bd.users_user_id = us.user_id " + + "LEFT JOIN settlement st ON bd.booking_id=st.booking_details_booking_id " + + "WHERE DATE(bd.booking_date) >= :fromDate " + + "AND DATE(bd.booking_date) <= :toDate " + + "AND bd.booking_status NOT IN ('PENDING')" + + "AND hd.zone = :zone " + + "AND (:refundStatus IS NULL OR bd.refund_status = :refundStatus) ", nativeQuery = true) + List getAllBookingsettlementDetailsByZoneWithStatus(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("zone") String zone, @Param("refundStatus") String refundStatus); + + + @Query(value = "SELECT " + + "h.hall_name AS HallName, " + + "h.hall_Incharge_name AS InchargeName, " + + "h.hall_Incharge_no AS hallInchargeMobno, " + + "CONCAT(h.zone, '/', h.division) AS ZoneDivision, " + // Concatenate zone and division + "COUNT(*) AS HallTotalBookings, " + + "SUM(p.amount_received) AS AmountReceived, " + + "COALESCE(SUM(r.amount - r.balace_amount), 0) AS AmountRefund, " + + "COALESCE(SUM(CASE WHEN bd.booking_status IN ('COMPLETED', 'CANCELED') THEN r.balace_amount ELSE 0 END), 0) AS Difference " + + "FROM " + + "booking_details bd " + + "JOIN " + + "hall_details h ON bd.hall_details_hall_id = h.hall_id " + + "LEFT JOIN users u ON bd.users_user_id = u.user_id " + + "JOIN " + + "payments p ON bd.booking_id = p.booking_details_booking_id " + + "LEFT JOIN refund_response r ON bd.booking_id = r.booking_id " + + "WHERE DATE(bd.booking_date) >= :fromDate " + + "AND DATE(bd.booking_date) <= :toDate " + + "AND bd.booking_status NOT IN ('PENDING')" + + "AND h.zone = :zone " + + "AND bd.hall_details_hall_id = :hall_id " + + "GROUP BY " + + "bd.hall_details_hall_id", nativeQuery = true) + List getBookingHallDetailsReportByZone1(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("zone") String zone, @Param("hall_id") Integer hallId); + + List findByHallDetailsAndBookingStatus(HallDetails hallDetails, BookingStatus gccBlocked); + + @Query(value = "SELECT COUNT(*) FROM booking_details WHERE hall_details_hall_id = :hallId AND start_date BETWEEN :startDate AND :endDate AND booking_status='GCC_BLOCKED'", nativeQuery = true) + int countByHallIdAndBookingDateBetween( + @Param("hallId") int hallId, + @Param("startDate") LocalDate startDate, + @Param("endDate") LocalDate endDate); + + @Query(value = "SELECT * FROM booking_details WHERE booking_id=:bookingId", nativeQuery = true) + List findBookingDetailsByBookingId(@Param("bookingId") Long bookingId); + + @Query(value = "SELECT booking_id FROM booking_details WHERE hall_details_hall_id = :hallId AND start_date BETWEEN :startDate AND :endDate AND booking_status='GCC_BLOCKED'", nativeQuery = true) + List findBookingIdsByHallIdAndBookingDateBetween(@Param("hallId") int hallId, @Param("startDate") LocalDate startDate, @Param("endDate") LocalDate endDate); + + @Query(value = "SELECT bd.*, hd.hall_name, us.name, us.usertype " + + "FROM booking_details bd " + + "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + + "LEFT JOIN users us ON bd.users_user_id = us.user_id " + + "LEFT JOIN settlement st ON bd.booking_id=st.booking_details_booking_id " + + "WHERE DATE(bd.booking_date) >= :fromDate " + + "AND DATE(bd.booking_date) <= :toDate " + + "AND bd.booking_status NOT IN ('PENDING')" + + "AND (:refundStatus IS NULL OR bd.refund_status = :refundStatus) ", nativeQuery = true) + List getAllBookingsettlementDetailsWithStatus(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("refundStatus") String refundStatus); + + @Query(value = "SELECT bd.*, hd.hall_name, us.name, us.usertype " + + "FROM booking_details bd " + + "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + + "LEFT JOIN users us ON bd.users_user_id = us.user_id " + + "LEFT JOIN settlement st ON bd.booking_id=st.booking_details_booking_id " + + "WHERE DATE(bd.booking_date) >= :fromDate " + + "AND bd.booking_status NOT IN ('PENDING')" + + "AND DATE(bd.booking_date) <= :toDate ", nativeQuery = true) + List getAllBookingsettlementDetails(@Param("fromDate") String fromDate, @Param("toDate") String toDate); + + + //admin dashboard + @Query(nativeQuery = true, value = - - //admin dashboard - @Query(nativeQuery = true, value = + "SELECT 'main' AS category, NULL AS `key` , " + - "SELECT 'main' AS category, NULL AS `key` , " + + "COUNT(DISTINCT CASE WHEN b.booking_status NOT IN ('GCC_BLOCKED', 'GCC_UNBLOCKED') THEN b.booking_id END) AS totalCount," + - "COUNT(DISTINCT CASE WHEN b.booking_status NOT IN ('GCC_BLOCKED', 'GCC_UNBLOCKED') THEN b.booking_id END) AS totalCount," + + "COALESCE(SUM(CASE WHEN b.booking_status NOT IN ('PENDING') THEN b.amount_received ELSE 0 END), 0) AS main_total_amount, " + - "COALESCE(SUM(CASE WHEN b.booking_status NOT IN ('PENDING') THEN b.amount_received ELSE 0 END), 0) AS main_total_amount, " + + "COALESCE(SUM(r.amount - r.balace_amount), 0) AS main_refunded_amount," + - "COALESCE(SUM(r.amount - r.balace_amount), 0) AS main_refunded_amount," + + "COALESCE(SUM(CASE WHEN b.booking_status NOT IN ('PENDING', 'REFUNDED', 'GCC_BLOCKED','REJECTED') THEN b.hall_amount ELSE 0 END), 0) AS main_net_amount, " + - "COALESCE(SUM(CASE WHEN b.booking_status NOT IN ('PENDING', 'REFUNDED', 'GCC_BLOCKED','REJECTED') THEN b.hall_amount ELSE 0 END), 0) AS main_net_amount, " + + "COALESCE(SUM(CASE WHEN b.booking_status NOT IN ('PENDING', 'REFUNDED', 'GCC_BLOCKED','REJECTED') THEN b.gst ELSE 0 END), 0) AS main_gst_amount, NULL AS PAST_Events, NULL AS FUTURE_Events " + - "COALESCE(SUM(CASE WHEN b.booking_status NOT IN ('PENDING', 'REFUNDED', 'GCC_BLOCKED','REJECTED') THEN b.gst ELSE 0 END), 0) AS main_gst_amount, NULL AS PAST_Events, NULL AS FUTURE_Events " + + "FROM booking_details b " + - "FROM booking_details b " + + "JOIN hall_details h ON h.hall_id = b.hall_details_hall_id " + - "JOIN hall_details h ON h.hall_id = b.hall_details_hall_id " + + "LEFT JOIN refund_response r ON b.booking_id = r.booking_id " + - "LEFT JOIN refund_response r ON b.booking_id = r.booking_id " + + "LEFT JOIN users u ON b.users_user_id = u.user_id " + - "LEFT JOIN users u ON b.users_user_id = u.user_id " + + "WHERE (b.start_date >= CASE WHEN :fromDate IS NOT NULL THEN :fromDate ELSE (SELECT MIN(start_date) FROM booking_details) END) " + - "WHERE (b.start_date >= CASE WHEN :fromDate IS NOT NULL THEN :fromDate ELSE (SELECT MIN(start_date) FROM booking_details) END) " + + "AND (b.start_date <= CASE WHEN :toDate IS NOT NULL THEN :toDate ELSE (SELECT MAX(end_date) FROM booking_details) END) " + - "AND (b.start_date <= CASE WHEN :toDate IS NOT NULL THEN :toDate ELSE (SELECT MAX(end_date) FROM booking_details) END) " + + "AND (:zone IS NULL OR :zone = 'ALL' OR h.zone = :zone) " + - "AND (:zone IS NULL OR :zone = 'ALL' OR h.zone = :zone) " + + "AND (:division IS NULL OR :division = 'ALL' OR h.division = :division) " + - "AND (:division IS NULL OR :division = 'ALL' OR h.division = :division) " + + "AND (:hall_id IS NULL OR :hall_id = '1000' OR h.hall_id = :hall_id) " + - "AND (:hall_id IS NULL OR :hall_id = '1000' OR h.hall_id = :hall_id) " + + "AND (:userType IS NULL OR :userType = 'ALL' OR u.usertype = :userType) " + - "AND (:userType IS NULL OR :userType = 'ALL' OR u.usertype = :userType) " + + "AND b.booking_status!='PENDING'" + - "AND b.booking_status!='PENDING'" + + "UNION ALL " + - "UNION ALL " + - + "SELECT 'bookingStatus' AS category, b.booking_status AS `key`, COUNT(*) AS totalCount, NULL AS main_total_amount, NULL AS main_refunded_amount, NULL AS main_net_amount,NULL AS main_gst_amount, NULL AS PAST_Events, NULL AS FUTURE_Events " + - "SELECT 'bookingStatus' AS category, b.booking_status AS `key`, COUNT(*) AS totalCount, NULL AS main_total_amount, NULL AS main_refunded_amount, NULL AS main_net_amount,NULL AS main_gst_amount, NULL AS PAST_Events, NULL AS FUTURE_Events " + + "FROM booking_details b " + - "FROM booking_details b " + + "JOIN hall_details h ON b.hall_details_hall_id = h.hall_id " + - "JOIN hall_details h ON b.hall_details_hall_id = h.hall_id " + + "LEFT JOIN users u ON b.users_user_id = u.user_id " + - "LEFT JOIN users u ON b.users_user_id = u.user_id " + + "WHERE (b.start_date >= CASE WHEN :fromDate IS NOT NULL THEN :fromDate ELSE (SELECT MIN(start_date) FROM booking_details) END) " + - "WHERE (b.start_date >= CASE WHEN :fromDate IS NOT NULL THEN :fromDate ELSE (SELECT MIN(start_date) FROM booking_details) END) " + + "AND (b.start_date <= CASE WHEN :toDate IS NOT NULL THEN :toDate ELSE (SELECT MAX(end_date) FROM booking_details) END) " + - "AND (b.start_date <= CASE WHEN :toDate IS NOT NULL THEN :toDate ELSE (SELECT MAX(end_date) FROM booking_details) END) " + + "AND (:zone IS NULL OR :zone = 'ALL' OR h.zone = :zone) " + - "AND (:zone IS NULL OR :zone = 'ALL' OR h.zone = :zone) " + + "AND (:division IS NULL OR :division = 'ALL' OR h.division = :division) " + - "AND (:division IS NULL OR :division = 'ALL' OR h.division = :division) " + + "AND (:hall_id IS NULL OR :hall_id = '1000' OR h.hall_id = :hall_id) " + - "AND (:hall_id IS NULL OR :hall_id = '1000' OR h.hall_id = :hall_id) " + + "AND (:userType IS NULL OR :userType = 'ALL' OR u.usertype = :userType) " + - "AND (:userType IS NULL OR :userType = 'ALL' OR u.usertype = :userType) " + + "AND b.booking_status != 'PENDING'" + - "AND b.booking_status != 'PENDING'"+ + "GROUP BY b.booking_status " + - "GROUP BY b.booking_status " + + "UNION ALL " + - "UNION ALL " + - + "SELECT 'refundStatus' AS category, b.refund_status AS `key`, COUNT(*) AS totalCount, NULL AS main_total_amount, NULL AS main_refunded_amount, NULL AS main_net_amount,NULL AS main_gst_amount, NULL AS PAST_Events, NULL AS FUTURE_Events " + - "SELECT 'refundStatus' AS category, b.refund_status AS `key`, COUNT(*) AS totalCount, NULL AS main_total_amount, NULL AS main_refunded_amount, NULL AS main_net_amount,NULL AS main_gst_amount, NULL AS PAST_Events, NULL AS FUTURE_Events " + + "FROM booking_details b " + - "FROM booking_details b " + + "JOIN hall_details h ON b.hall_details_hall_id = h.hall_id " + - "JOIN hall_details h ON b.hall_details_hall_id = h.hall_id " + + "LEFT JOIN users u ON b.users_user_id = u.user_id " + - "LEFT JOIN users u ON b.users_user_id = u.user_id " + + "WHERE (b.start_date >= CASE WHEN :fromDate IS NOT NULL THEN :fromDate ELSE (SELECT MIN(start_date) FROM booking_details) END) " + - "WHERE (b.start_date >= CASE WHEN :fromDate IS NOT NULL THEN :fromDate ELSE (SELECT MIN(start_date) FROM booking_details) END) " + + "AND (b.start_date <= CASE WHEN :toDate IS NOT NULL THEN :toDate ELSE (SELECT MAX(end_date) FROM booking_details) END) " + - "AND (b.start_date <= CASE WHEN :toDate IS NOT NULL THEN :toDate ELSE (SELECT MAX(end_date) FROM booking_details) END) " + + "AND (:zone IS NULL OR :zone = 'ALL' OR h.zone = :zone) " + - "AND (:zone IS NULL OR :zone = 'ALL' OR h.zone = :zone) " + + "AND (:division IS NULL OR :division = 'ALL' OR h.division = :division) " + - "AND (:division IS NULL OR :division = 'ALL' OR h.division = :division) " + + "AND (:hall_id IS NULL OR :hall_id = '1000' OR h.hall_id = :hall_id) " + - "AND (:hall_id IS NULL OR :hall_id = '1000' OR h.hall_id = :hall_id) " + + "AND (:userType IS NULL OR :userType = 'ALL' OR u.usertype = :userType) " + - "AND (:userType IS NULL OR :userType = 'ALL' OR u.usertype = :userType) " + + "AND b.booking_status != 'PENDING'" + - "AND b.booking_status != 'PENDING'"+ + "GROUP BY b.refund_status " + - "GROUP BY b.refund_status " + + "UNION ALL " + - "UNION ALL " + - + "SELECT 'reason' AS category, b.reason AS `key`, COUNT(*) AS totalCount, NULL AS main_total_amount, NULL AS main_net_amount, NULL AS main_refunded_amount,NULL AS main_gst_amount, NULL AS PAST_Events, NULL AS FUTURE_Events " + - "SELECT 'reason' AS category, b.reason AS `key`, COUNT(*) AS totalCount, NULL AS main_total_amount, NULL AS main_net_amount, NULL AS main_refunded_amount,NULL AS main_gst_amount, NULL AS PAST_Events, NULL AS FUTURE_Events " + + "FROM booking_details b " + - "FROM booking_details b " + + "JOIN hall_details h ON b.hall_details_hall_id = h.hall_id " + - "JOIN hall_details h ON b.hall_details_hall_id = h.hall_id " + + "LEFT JOIN users u ON b.users_user_id = u.user_id " + - "LEFT JOIN users u ON b.users_user_id = u.user_id " + + "WHERE (b.start_date >= CASE WHEN :fromDate IS NOT NULL THEN :fromDate ELSE (SELECT MIN(start_date) FROM booking_details) END) " + - "WHERE (b.start_date >= CASE WHEN :fromDate IS NOT NULL THEN :fromDate ELSE (SELECT MIN(start_date) FROM booking_details) END) " + + "AND (b.start_date <= CASE WHEN :toDate IS NOT NULL THEN :toDate ELSE (SELECT MAX(end_date) FROM booking_details) END) " + - "AND (b.start_date <= CASE WHEN :toDate IS NOT NULL THEN :toDate ELSE (SELECT MAX(end_date) FROM booking_details) END) " + + "AND (:zone IS NULL OR :zone = 'ALL' OR h.zone = :zone) " + - "AND (:zone IS NULL OR :zone = 'ALL' OR h.zone = :zone) " + + "AND (:division IS NULL OR :division = 'ALL' OR h.division = :division) " + - "AND (:division IS NULL OR :division = 'ALL' OR h.division = :division) " + + "AND (:hall_id IS NULL OR :hall_id = '1000' OR h.hall_id = :hall_id) " + - "AND (:hall_id IS NULL OR :hall_id = '1000' OR h.hall_id = :hall_id) " + + "AND (:userType IS NULL OR :userType = 'ALL' OR u.usertype = :userType) " + - "AND (:userType IS NULL OR :userType = 'ALL' OR u.usertype = :userType) " + + "AND b.booking_status != 'PENDING'" + - "AND b.booking_status != 'PENDING'"+ + "GROUP BY b.reason " + - "GROUP BY b.reason " + + "UNION ALL " + - "UNION ALL " + - + "SELECT 'zonewise' AS category, h.zone AS `key`, SUM(CASE WHEN b.hall_details_hall_id IS NOT NULL AND b.booking_status != 'PENDING' THEN 1 ELSE 0 END) AS totalCount, " + - "SELECT 'zonewise' AS category, h.zone AS `key`, SUM(CASE WHEN b.hall_details_hall_id IS NOT NULL AND b.booking_status != 'PENDING' THEN 1 ELSE 0 END) AS totalCount, " + + "NULL AS main_total_amount, NULL AS main_refunded_amount, NULL AS main_net_amount,NULL AS main_gst_amount, NULL AS PAST_Events, NULL AS FUTURE_Events " + - "NULL AS main_total_amount, NULL AS main_refunded_amount, NULL AS main_net_amount,NULL AS main_gst_amount, NULL AS PAST_Events, NULL AS FUTURE_Events " + + "FROM hall_details h " + - "FROM hall_details h " + + "LEFT JOIN booking_details b ON b.hall_details_hall_id = h.hall_id " + - "LEFT JOIN booking_details b ON b.hall_details_hall_id = h.hall_id " + + "LEFT JOIN users u ON b.users_user_id = u.user_id " + - "LEFT JOIN users u ON b.users_user_id = u.user_id " + + "WHERE (b.start_date IS NULL OR b.start_date BETWEEN COALESCE(:fromDate, (SELECT MIN(start_date) FROM booking_details)) AND COALESCE(:toDate, (SELECT MAX(end_date) FROM booking_details))) " + - "WHERE (b.start_date IS NULL OR b.start_date BETWEEN COALESCE(:fromDate, (SELECT MIN(start_date) FROM booking_details)) AND COALESCE(:toDate, (SELECT MAX(end_date) FROM booking_details))) " + + "AND (:zone IS NULL OR :zone = 'ALL' OR h.zone = :zone) " + - "AND (:zone IS NULL OR :zone = 'ALL' OR h.zone = :zone) " + + "AND (:division IS NULL OR :division = 'ALL' OR h.division = :division) " + - "AND (:division IS NULL OR :division = 'ALL' OR h.division = :division) " + + "AND (:hall_id IS NULL OR :hall_id = '1000' OR h.hall_id = :hall_id) " + - "AND (:hall_id IS NULL OR :hall_id = '1000' OR h.hall_id = :hall_id) " + + "AND (:userType IS NULL OR :userType = 'ALL' OR u.usertype = :userType) " + - "AND (:userType IS NULL OR :userType = 'ALL' OR u.usertype = :userType) " + + "GROUP BY h.zone " + - "GROUP BY h.zone " + + "UNION ALL " + - "UNION ALL " + - + "SELECT 'paymentStatus' AS category, " + - "SELECT 'paymentStatus' AS category, " + + " p.payment_status AS `key`, " + - " p.payment_status AS `key`, " + + " COUNT(*) AS totalCount, " + - " COUNT(*) AS totalCount, " + + " NULL AS main_total_amount, " + - " NULL AS main_total_amount, " + + " NULL AS main_refunded_amount, " + - " NULL AS main_refunded_amount, " + + " NULL AS main_net_amount, " + - " NULL AS main_net_amount, " + + " NULL AS main_gst_amount," + - " NULL AS main_gst_amount,"+ + " NULL AS PAST_Events, " + - " NULL AS PAST_Events, " + + " NULL AS FUTURE_Events " + - " NULL AS FUTURE_Events " + + "FROM payments p " + - "FROM payments p " + + "JOIN booking_details b ON p.booking_details_booking_id = b.booking_id " + - "JOIN booking_details b ON p.booking_details_booking_id = b.booking_id " + + "JOIN hall_details h ON b.hall_details_hall_id = h.hall_id " + - "JOIN hall_details h ON b.hall_details_hall_id = h.hall_id " + + "LEFT JOIN users u ON b.users_user_id = u.user_id " + - "LEFT JOIN users u ON b.users_user_id = u.user_id " + + "WHERE (b.start_date >= CASE WHEN :fromDate IS NOT NULL THEN :fromDate ELSE (SELECT MIN(start_date) FROM booking_details) END) " + - "WHERE (b.start_date >= CASE WHEN :fromDate IS NOT NULL THEN :fromDate ELSE (SELECT MIN(start_date) FROM booking_details) END) " + + "AND (b.start_date <= CASE WHEN :toDate IS NOT NULL THEN :toDate ELSE (SELECT MAX(end_date) FROM booking_details) END) " + - "AND (b.start_date <= CASE WHEN :toDate IS NOT NULL THEN :toDate ELSE (SELECT MAX(end_date) FROM booking_details) END) " + + "AND (:zone IS NULL OR :zone = 'ALL' OR h.zone = :zone) " + - "AND (:zone IS NULL OR :zone = 'ALL' OR h.zone = :zone) " + + "AND (:division IS NULL OR :division = 'ALL' OR h.division = :division) " + - "AND (:division IS NULL OR :division = 'ALL' OR h.division = :division) " + + "AND (:hall_id IS NULL OR :hall_id = '1000' OR h.hall_id = :hall_id) " + - "AND (:hall_id IS NULL OR :hall_id = '1000' OR h.hall_id = :hall_id) " + + "AND (:userType IS NULL OR :userType = 'ALL' OR u.usertype = :userType) " + - "AND (:userType IS NULL OR :userType = 'ALL' OR u.usertype = :userType) " + + "AND b.booking_status!='PENDING'" + - "AND b.booking_status!='PENDING'" + + "GROUP BY p.payment_status " + - "GROUP BY p.payment_status " + + "UNION ALL " + - "UNION ALL " + - + "SELECT 'past_future' AS category, NULL AS `key`, NULL AS totalCount, NULL AS main_total_amount, NULL AS main_refunded_amount, NULL AS main_net_amount, " + + "NULL AS main_gst_amount," + + "COALESCE(SUM(PAST_Booking), 0) AS PAST_Events, " + + "COALESCE(SUM(FUTURE_Booking), 0) AS FUTURE_Events " + + "FROM ( " + + "SELECT " + + "CASE WHEN DATE(b.start_date) < CURRENT_DATE() THEN 1 ELSE 0 END AS PAST_Booking, " + + "CASE WHEN DATE(b.start_date) BETWEEN CURRENT_DATE() AND DATE_ADD(CURRENT_DATE(), INTERVAL 3 MONTH) THEN 1 ELSE 0 END AS FUTURE_Booking " + + "FROM booking_details b " + + "JOIN hall_details h ON b.hall_details_hall_id = h.hall_id " + + "LEFT JOIN users u ON b.users_user_id = u.user_id " + + "WHERE " + + " b.booking_status!='PENDING'" + + "AND (b.start_date >= CASE WHEN :fromDate IS NOT NULL THEN :fromDate ELSE (SELECT MIN(start_date) FROM booking_details) END) AND " + + "(b.start_date <= CASE WHEN :toDate IS NOT NULL THEN :toDate ELSE (SELECT MAX(end_date) FROM booking_details) END) AND " + + "(:zone IS NULL OR :zone = 'ALL' OR h.zone = :zone) AND " + + "(:division IS NULL OR :division = 'ALL' OR h.division = :division) AND " + + "(:hall_id IS NULL OR :hall_id = '1000' OR h.hall_id = :hall_id) AND " + + "(:userType IS NULL OR :userType = 'ALL' OR u.usertype = :userType) " + + ") AS combined" + + ) + List> getBookingStatistics( + @Param("fromDate") LocalDate fromDate, + @Param("toDate") LocalDate toDate, + @Param("zone") String zone, + @Param("division") String division, + @Param("hall_id") Integer hallid, + @Param("userType") String userType + ); + + @Query(value = "SELECT \r\n" + + " b.booking_date as booking_date,\r\n" + + " u.name as name,\r\n" + + " u.usertype as usertype,\r\n" + + " b.reason as reason,\r\n" + + " b.start_date as start_date,\r\n" + + " b.end_date as end_date,\r\n" + + " b.no_of_days as no_of_days,\r\n" + + " b.booking_status as booking_status,\r\n" + + " b.amount_received as amount_received,\r\n" + + " COALESCE(rt.amount_refunded, 0) as amount_refunded,\r\n" + + " COALESCE(r.balace_amount, 0) as balance_amount\r\n" + + "FROM booking_details b\r\n" + + "JOIN hall_details h ON b.hall_details_hall_id = h.hall_id \r\n" + + "LEFT JOIN users u ON b.users_user_id = u.user_id\r\n" + + "LEFT JOIN refund_response r ON b.booking_id = r.booking_id\r\n" + + "LEFT JOIN refund_transaction rt ON b.booking_id = rt.booking_details_booking_id\r\n" + + "WHERE h.hall_id = :hallId AND b.booking_status != 'PENDING' ", nativeQuery = true) + List> getBookingDetailsByHallId(@Param("hallId") int hallId); + + //officer Dashboard + @Query(nativeQuery = true, value = + "SELECT 'main' AS category, NULL AS `key` , " + + "COUNT(DISTINCT b.booking_id) AS totalCount," + + "SUM(b.amount_received) AS main_total_amount, " + + "COALESCE(SUM(r.amount-r.balace_amount),0) AS main_refunded_amount, " + + "COALESCE(SUM(CASE WHEN b.booking_status IN ('COMPLETED', 'CANCELED') THEN r.balace_amount ELSE 0 END), 0) AS main_net_amount, NULL AS PAST_Events, NULL AS FUTURE_Events " + + "FROM booking_details b " + + "JOIN hall_details h ON h.hall_id = b.hall_details_hall_id " + + "LEFT JOIN refund_response r ON b.booking_id = r.booking_id " + + "LEFT JOIN users u ON b.users_user_id = u.user_id " + + "WHERE (b.start_date >= CASE WHEN :fromDate IS NOT NULL THEN :fromDate ELSE (SELECT MIN(start_date) FROM booking_details) END) " + + "AND (b.start_date <= CASE WHEN :toDate IS NOT NULL THEN :toDate ELSE (SELECT MAX(end_date) FROM booking_details) END) " + + "AND (:zone IS NULL OR :zone = 'ALL' OR h.zone = :zone) " + + "AND (:division IS NULL OR :division = 'ALL' OR h.division = :division) " + + "AND (:hall_id IS NULL OR :hall_id = '1000' OR h.hall_id = :hall_id) " + + "AND (:userType IS NULL OR :userType = 'ALL' OR u.usertype = :userType) " + + "AND b.booking_status!='PENDING'" + + "UNION ALL " + + + "SELECT 'bookingStatus' AS category, b.booking_status AS `key`, COUNT(*) AS totalCount, NULL AS main_total_amount, NULL AS main_refunded_amount, NULL AS main_net_amount, NULL AS PAST_Events, NULL AS FUTURE_Events " + + "FROM booking_details b " + + "JOIN hall_details h ON b.hall_details_hall_id = h.hall_id " + + "LEFT JOIN users u ON b.users_user_id = u.user_id " + + "WHERE (b.start_date >= CASE WHEN :fromDate IS NOT NULL THEN :fromDate ELSE (SELECT MIN(start_date) FROM booking_details) END) " + + "AND (b.start_date <= CASE WHEN :toDate IS NOT NULL THEN :toDate ELSE (SELECT MAX(end_date) FROM booking_details) END) " + + "AND (:zone IS NULL OR :zone = 'ALL' OR h.zone = :zone) " + + "AND (:division IS NULL OR :division = 'ALL' OR h.division = :division) " + + "AND (:hall_id IS NULL OR :hall_id = '1000' OR h.hall_id = :hall_id) " + + "AND (:userType IS NULL OR :userType = 'ALL' OR u.usertype = :userType) " + + "AND b.booking_status != 'PENDING'" + + "GROUP BY b.booking_status " + + "UNION ALL " + + + "SELECT 'refundStatus' AS category, b.refund_status AS `key`, COUNT(*) AS totalCount, NULL AS main_total_amount, NULL AS main_refunded_amount, NULL AS main_net_amount, NULL AS PAST_Events, NULL AS FUTURE_Events " + + "FROM booking_details b " + + "JOIN hall_details h ON b.hall_details_hall_id = h.hall_id " + + "LEFT JOIN users u ON b.users_user_id = u.user_id " + + "WHERE (b.start_date >= CASE WHEN :fromDate IS NOT NULL THEN :fromDate ELSE (SELECT MIN(start_date) FROM booking_details) END) " + + "AND (b.start_date <= CASE WHEN :toDate IS NOT NULL THEN :toDate ELSE (SELECT MAX(end_date) FROM booking_details) END) " + + "AND (:zone IS NULL OR :zone = 'ALL' OR h.zone = :zone) " + + "AND (:division IS NULL OR :division = 'ALL' OR h.division = :division) " + + "AND (:hall_id IS NULL OR :hall_id = '1000' OR h.hall_id = :hall_id) " + + "AND (:userType IS NULL OR :userType = 'ALL' OR u.usertype = :userType) " + + "AND b.booking_status != 'PENDING'" + + "GROUP BY b.refund_status " + + "UNION ALL " + + + "SELECT 'reason' AS category, b.reason AS `key`, COUNT(*) AS totalCount, NULL AS main_total_amount, NULL AS main_net_amount, NULL AS main_refunded_amount, NULL AS PAST_Events, NULL AS FUTURE_Events " + + "FROM booking_details b " + + "JOIN hall_details h ON b.hall_details_hall_id = h.hall_id " + + "LEFT JOIN users u ON b.users_user_id = u.user_id " + + "WHERE (b.start_date >= CASE WHEN :fromDate IS NOT NULL THEN :fromDate ELSE (SELECT MIN(start_date) FROM booking_details) END) " + + "AND (b.start_date <= CASE WHEN :toDate IS NOT NULL THEN :toDate ELSE (SELECT MAX(end_date) FROM booking_details) END) " + + "AND (:zone IS NULL OR :zone = 'ALL' OR h.zone = :zone) " + + "AND (:division IS NULL OR :division = 'ALL' OR h.division = :division) " + + "AND (:hall_id IS NULL OR :hall_id = '1000' OR h.hall_id = :hall_id) " + + "AND (:userType IS NULL OR :userType = 'ALL' OR u.usertype = :userType) " + + "AND b.booking_status != 'PENDING'" + + "GROUP BY b.reason " + + "UNION ALL " + + + "SELECT 'zonewise' AS category, h.zone AS `key`, SUM(CASE WHEN b.hall_details_hall_id IS NOT NULL AND b.booking_status != 'PENDING' THEN 1 ELSE 0 END) AS totalCount, " + + "NULL AS main_total_amount, NULL AS main_refunded_amount, NULL AS main_net_amount, NULL AS PAST_Events, NULL AS FUTURE_Events " + + "FROM hall_details h " + + "LEFT JOIN booking_details b ON b.hall_details_hall_id = h.hall_id " + + "LEFT JOIN users u ON b.users_user_id = u.user_id " + + "WHERE (b.start_date IS NULL OR b.start_date BETWEEN COALESCE(:fromDate, (SELECT MIN(start_date) FROM booking_details)) AND COALESCE(:toDate, (SELECT MAX(end_date) FROM booking_details))) " + + "AND (:zone IS NULL OR :zone = 'ALL' OR h.zone = :zone) " + + "AND (:division IS NULL OR :division = 'ALL' OR h.division = :division) " + + "AND (:hall_id IS NULL OR :hall_id = '1000' OR h.hall_id = :hall_id) " + + "AND (:userType IS NULL OR :userType = 'ALL' OR u.usertype = :userType) " + + "GROUP BY h.zone " + + "UNION ALL " + + + "SELECT 'paymentStatus' AS category, " + + " p.payment_status AS `key`, " + + " COUNT(*) AS totalCount, " + + " NULL AS main_total_amount, " + + " NULL AS main_refunded_amount, " + + " NULL AS main_net_amount, " + + " NULL AS PAST_Events, " + + " NULL AS FUTURE_Events " + + "FROM payments p " + + "JOIN booking_details b ON p.booking_details_booking_id = b.booking_id " + + "JOIN hall_details h ON b.hall_details_hall_id = h.hall_id " + + "LEFT JOIN users u ON b.users_user_id = u.user_id " + + "WHERE (b.start_date >= CASE WHEN :fromDate IS NOT NULL THEN :fromDate ELSE (SELECT MIN(start_date) FROM booking_details) END) " + + "AND (b.start_date <= CASE WHEN :toDate IS NOT NULL THEN :toDate ELSE (SELECT MAX(end_date) FROM booking_details) END) " + + "AND (:zone IS NULL OR :zone = 'ALL' OR h.zone = :zone) " + + "AND (:division IS NULL OR :division = 'ALL' OR h.division = :division) " + + "AND (:hall_id IS NULL OR :hall_id = '1000' OR h.hall_id = :hall_id) " + + "AND (:userType IS NULL OR :userType = 'ALL' OR u.usertype = :userType) " + + "AND b.booking_status!='PENDING'" + + "GROUP BY p.payment_status " + + "UNION ALL " + + + "SELECT 'past_future' AS category, NULL AS `key`, NULL AS totalCount, NULL AS main_total_amount, NULL AS main_refunded_amount, NULL AS main_net_amount, " + + "COALESCE(SUM(PAST_Booking), 0) AS PAST_Events, " + + "COALESCE(SUM(FUTURE_Booking), 0) AS FUTURE_Events " + + "FROM ( " + + "SELECT " + + "CASE WHEN DATE(b.start_date) < CURRENT_DATE() THEN 1 ELSE 0 END AS PAST_Booking, " + + "CASE WHEN DATE(b.start_date) BETWEEN CURRENT_DATE() AND DATE_ADD(CURRENT_DATE(), INTERVAL 3 MONTH) THEN 1 ELSE 0 END AS FUTURE_Booking " + + "FROM booking_details b " + + "JOIN hall_details h ON b.hall_details_hall_id = h.hall_id " + + "LEFT JOIN users u ON b.users_user_id = u.user_id " + + "WHERE " + + " b.booking_status!='PENDING'" + + "AND (b.start_date >= CASE WHEN :fromDate IS NOT NULL THEN :fromDate ELSE (SELECT MIN(start_date) FROM booking_details) END) AND " + + "(b.start_date <= CASE WHEN :toDate IS NOT NULL THEN :toDate ELSE (SELECT MAX(end_date) FROM booking_details) END) AND " + + "(:zone IS NULL OR :zone = 'ALL' OR h.zone = :zone) AND " + + "(:division IS NULL OR :division = 'ALL' OR h.division = :division) AND " + + "(:hall_id IS NULL OR :hall_id = '1000' OR h.hall_id = :hall_id) AND " + + "(:userType IS NULL OR :userType = 'ALL' OR u.usertype = :userType) " + + ") AS combined" + ) + List> getOfficerDashboard( + @Param("fromDate") LocalDate fromDate, + @Param("toDate") LocalDate toDate, + @Param("zone") String zone, + @Param("division") String division, + @Param("hall_id") Integer hallid, + @Param("userType") String userType + ); - "SELECT 'past_future' AS category, NULL AS `key`, NULL AS totalCount, NULL AS main_total_amount, NULL AS main_refunded_amount, NULL AS main_net_amount, " + - "NULL AS main_gst_amount,"+ - "COALESCE(SUM(PAST_Booking), 0) AS PAST_Events, " + - "COALESCE(SUM(FUTURE_Booking), 0) AS FUTURE_Events " + - "FROM ( " + - "SELECT " + - "CASE WHEN DATE(b.start_date) < CURRENT_DATE() THEN 1 ELSE 0 END AS PAST_Booking, " + - "CASE WHEN DATE(b.start_date) BETWEEN CURRENT_DATE() AND DATE_ADD(CURRENT_DATE(), INTERVAL 3 MONTH) THEN 1 ELSE 0 END AS FUTURE_Booking " + - "FROM booking_details b " + - "JOIN hall_details h ON b.hall_details_hall_id = h.hall_id " + - "LEFT JOIN users u ON b.users_user_id = u.user_id " + - "WHERE " + - " b.booking_status!='PENDING'" + - "AND (b.start_date >= CASE WHEN :fromDate IS NOT NULL THEN :fromDate ELSE (SELECT MIN(start_date) FROM booking_details) END) AND " + - "(b.start_date <= CASE WHEN :toDate IS NOT NULL THEN :toDate ELSE (SELECT MAX(end_date) FROM booking_details) END) AND " + - "(:zone IS NULL OR :zone = 'ALL' OR h.zone = :zone) AND " + - "(:division IS NULL OR :division = 'ALL' OR h.division = :division) AND " + - "(:hall_id IS NULL OR :hall_id = '1000' OR h.hall_id = :hall_id) AND " + - "(:userType IS NULL OR :userType = 'ALL' OR u.usertype = :userType) " + - ") AS combined" - - ) - List> getBookingStatistics( - @Param("fromDate") LocalDate fromDate, - @Param("toDate") LocalDate toDate, - @Param("zone") String zone, - @Param("division") String division, - @Param("hall_id") Integer hallid, - @Param("userType") String userType - ); - - @Query(value = "SELECT \r\n" - + " b.booking_date as booking_date,\r\n" - + " u.name as name,\r\n" - + " u.usertype as usertype,\r\n" - + " b.reason as reason,\r\n" - + " b.start_date as start_date,\r\n" - + " b.end_date as end_date,\r\n" - + " b.no_of_days as no_of_days,\r\n" - + " b.booking_status as booking_status,\r\n" - + " b.amount_received as amount_received,\r\n" - + " COALESCE(rt.amount_refunded, 0) as amount_refunded,\r\n" - + " COALESCE(r.balace_amount, 0) as balance_amount\r\n" - + "FROM booking_details b\r\n" - + "JOIN hall_details h ON b.hall_details_hall_id = h.hall_id \r\n" - + "LEFT JOIN users u ON b.users_user_id = u.user_id\r\n" - + "LEFT JOIN refund_response r ON b.booking_id = r.booking_id\r\n" - + "LEFT JOIN refund_transaction rt ON b.booking_id = rt.booking_details_booking_id\r\n" - + "WHERE h.hall_id = :hallId AND b.booking_status != 'PENDING' ", nativeQuery = true) - List> getBookingDetailsByHallId(@Param("hallId") int hallId); - - //officer Dashboard - @Query(nativeQuery = true, value = - "SELECT 'main' AS category, NULL AS `key` , " + - "COUNT(DISTINCT b.booking_id) AS totalCount," + - "SUM(b.amount_received) AS main_total_amount, " + - "COALESCE(SUM(r.amount-r.balace_amount),0) AS main_refunded_amount, " + - "COALESCE(SUM(CASE WHEN b.booking_status IN ('COMPLETED', 'CANCELED') THEN r.balace_amount ELSE 0 END), 0) AS main_net_amount, NULL AS PAST_Events, NULL AS FUTURE_Events " + - "FROM booking_details b " + - "JOIN hall_details h ON h.hall_id = b.hall_details_hall_id " + - "LEFT JOIN refund_response r ON b.booking_id = r.booking_id " + - "LEFT JOIN users u ON b.users_user_id = u.user_id " + - "WHERE (b.start_date >= CASE WHEN :fromDate IS NOT NULL THEN :fromDate ELSE (SELECT MIN(start_date) FROM booking_details) END) " + - "AND (b.start_date <= CASE WHEN :toDate IS NOT NULL THEN :toDate ELSE (SELECT MAX(end_date) FROM booking_details) END) " + - "AND (:zone IS NULL OR :zone = 'ALL' OR h.zone = :zone) " + - "AND (:division IS NULL OR :division = 'ALL' OR h.division = :division) " + - "AND (:hall_id IS NULL OR :hall_id = '1000' OR h.hall_id = :hall_id) " + - "AND (:userType IS NULL OR :userType = 'ALL' OR u.usertype = :userType) " + - "AND b.booking_status!='PENDING'" + - "UNION ALL " + - - "SELECT 'bookingStatus' AS category, b.booking_status AS `key`, COUNT(*) AS totalCount, NULL AS main_total_amount, NULL AS main_refunded_amount, NULL AS main_net_amount, NULL AS PAST_Events, NULL AS FUTURE_Events " + - "FROM booking_details b " + - "JOIN hall_details h ON b.hall_details_hall_id = h.hall_id " + - "LEFT JOIN users u ON b.users_user_id = u.user_id " + - "WHERE (b.start_date >= CASE WHEN :fromDate IS NOT NULL THEN :fromDate ELSE (SELECT MIN(start_date) FROM booking_details) END) " + - "AND (b.start_date <= CASE WHEN :toDate IS NOT NULL THEN :toDate ELSE (SELECT MAX(end_date) FROM booking_details) END) " + - "AND (:zone IS NULL OR :zone = 'ALL' OR h.zone = :zone) " + - "AND (:division IS NULL OR :division = 'ALL' OR h.division = :division) " + - "AND (:hall_id IS NULL OR :hall_id = '1000' OR h.hall_id = :hall_id) " + - "AND (:userType IS NULL OR :userType = 'ALL' OR u.usertype = :userType) " + - "AND b.booking_status != 'PENDING'"+ - "GROUP BY b.booking_status " + - "UNION ALL " + - - "SELECT 'refundStatus' AS category, b.refund_status AS `key`, COUNT(*) AS totalCount, NULL AS main_total_amount, NULL AS main_refunded_amount, NULL AS main_net_amount, NULL AS PAST_Events, NULL AS FUTURE_Events " + - "FROM booking_details b " + - "JOIN hall_details h ON b.hall_details_hall_id = h.hall_id " + - "LEFT JOIN users u ON b.users_user_id = u.user_id " + - "WHERE (b.start_date >= CASE WHEN :fromDate IS NOT NULL THEN :fromDate ELSE (SELECT MIN(start_date) FROM booking_details) END) " + - "AND (b.start_date <= CASE WHEN :toDate IS NOT NULL THEN :toDate ELSE (SELECT MAX(end_date) FROM booking_details) END) " + - "AND (:zone IS NULL OR :zone = 'ALL' OR h.zone = :zone) " + - "AND (:division IS NULL OR :division = 'ALL' OR h.division = :division) " + - "AND (:hall_id IS NULL OR :hall_id = '1000' OR h.hall_id = :hall_id) " + - "AND (:userType IS NULL OR :userType = 'ALL' OR u.usertype = :userType) " + - "AND b.booking_status != 'PENDING'"+ - "GROUP BY b.refund_status " + - "UNION ALL " + - - "SELECT 'reason' AS category, b.reason AS `key`, COUNT(*) AS totalCount, NULL AS main_total_amount, NULL AS main_net_amount, NULL AS main_refunded_amount, NULL AS PAST_Events, NULL AS FUTURE_Events " + - "FROM booking_details b " + - "JOIN hall_details h ON b.hall_details_hall_id = h.hall_id " + - "LEFT JOIN users u ON b.users_user_id = u.user_id " + - "WHERE (b.start_date >= CASE WHEN :fromDate IS NOT NULL THEN :fromDate ELSE (SELECT MIN(start_date) FROM booking_details) END) " + - "AND (b.start_date <= CASE WHEN :toDate IS NOT NULL THEN :toDate ELSE (SELECT MAX(end_date) FROM booking_details) END) " + - "AND (:zone IS NULL OR :zone = 'ALL' OR h.zone = :zone) " + - "AND (:division IS NULL OR :division = 'ALL' OR h.division = :division) " + - "AND (:hall_id IS NULL OR :hall_id = '1000' OR h.hall_id = :hall_id) " + - "AND (:userType IS NULL OR :userType = 'ALL' OR u.usertype = :userType) " + - "AND b.booking_status != 'PENDING'"+ - "GROUP BY b.reason " + - "UNION ALL " + - - "SELECT 'zonewise' AS category, h.zone AS `key`, SUM(CASE WHEN b.hall_details_hall_id IS NOT NULL AND b.booking_status != 'PENDING' THEN 1 ELSE 0 END) AS totalCount, " + - "NULL AS main_total_amount, NULL AS main_refunded_amount, NULL AS main_net_amount, NULL AS PAST_Events, NULL AS FUTURE_Events " + - "FROM hall_details h " + - "LEFT JOIN booking_details b ON b.hall_details_hall_id = h.hall_id " + - "LEFT JOIN users u ON b.users_user_id = u.user_id " + - "WHERE (b.start_date IS NULL OR b.start_date BETWEEN COALESCE(:fromDate, (SELECT MIN(start_date) FROM booking_details)) AND COALESCE(:toDate, (SELECT MAX(end_date) FROM booking_details))) " + - "AND (:zone IS NULL OR :zone = 'ALL' OR h.zone = :zone) " + - "AND (:division IS NULL OR :division = 'ALL' OR h.division = :division) " + - "AND (:hall_id IS NULL OR :hall_id = '1000' OR h.hall_id = :hall_id) " + - "AND (:userType IS NULL OR :userType = 'ALL' OR u.usertype = :userType) " + - "GROUP BY h.zone " + - "UNION ALL " + - - "SELECT 'paymentStatus' AS category, " + - " p.payment_status AS `key`, " + - " COUNT(*) AS totalCount, " + - " NULL AS main_total_amount, " + - " NULL AS main_refunded_amount, " + - " NULL AS main_net_amount, " + - " NULL AS PAST_Events, " + - " NULL AS FUTURE_Events " + - "FROM payments p " + - "JOIN booking_details b ON p.booking_details_booking_id = b.booking_id " + - "JOIN hall_details h ON b.hall_details_hall_id = h.hall_id " + - "LEFT JOIN users u ON b.users_user_id = u.user_id " + - "WHERE (b.start_date >= CASE WHEN :fromDate IS NOT NULL THEN :fromDate ELSE (SELECT MIN(start_date) FROM booking_details) END) " + - "AND (b.start_date <= CASE WHEN :toDate IS NOT NULL THEN :toDate ELSE (SELECT MAX(end_date) FROM booking_details) END) " + - "AND (:zone IS NULL OR :zone = 'ALL' OR h.zone = :zone) " + - "AND (:division IS NULL OR :division = 'ALL' OR h.division = :division) " + - "AND (:hall_id IS NULL OR :hall_id = '1000' OR h.hall_id = :hall_id) " + - "AND (:userType IS NULL OR :userType = 'ALL' OR u.usertype = :userType) " + - "AND b.booking_status!='PENDING'" + - "GROUP BY p.payment_status " + - "UNION ALL " + - - "SELECT 'past_future' AS category, NULL AS `key`, NULL AS totalCount, NULL AS main_total_amount, NULL AS main_refunded_amount, NULL AS main_net_amount, " + - "COALESCE(SUM(PAST_Booking), 0) AS PAST_Events, " + - "COALESCE(SUM(FUTURE_Booking), 0) AS FUTURE_Events " + - "FROM ( " + - "SELECT " + - "CASE WHEN DATE(b.start_date) < CURRENT_DATE() THEN 1 ELSE 0 END AS PAST_Booking, " + - "CASE WHEN DATE(b.start_date) BETWEEN CURRENT_DATE() AND DATE_ADD(CURRENT_DATE(), INTERVAL 3 MONTH) THEN 1 ELSE 0 END AS FUTURE_Booking " + - "FROM booking_details b " + - "JOIN hall_details h ON b.hall_details_hall_id = h.hall_id " + - "LEFT JOIN users u ON b.users_user_id = u.user_id " + - "WHERE " + - " b.booking_status!='PENDING'" + - "AND (b.start_date >= CASE WHEN :fromDate IS NOT NULL THEN :fromDate ELSE (SELECT MIN(start_date) FROM booking_details) END) AND " + - "(b.start_date <= CASE WHEN :toDate IS NOT NULL THEN :toDate ELSE (SELECT MAX(end_date) FROM booking_details) END) AND " + - "(:zone IS NULL OR :zone = 'ALL' OR h.zone = :zone) AND " + - "(:division IS NULL OR :division = 'ALL' OR h.division = :division) AND " + - "(:hall_id IS NULL OR :hall_id = '1000' OR h.hall_id = :hall_id) AND " + - "(:userType IS NULL OR :userType = 'ALL' OR u.usertype = :userType) " + - ") AS combined" - ) - List> getOfficerDashboard( - @Param("fromDate") LocalDate fromDate, - @Param("toDate") LocalDate toDate, - @Param("zone") String zone, - @Param("division") String division, - @Param("hall_id") Integer hallid, - @Param("userType") String userType - ); - @Query(value = "SELECT \r\n" - + " b.booking_date as booking_date,\r\n" - + " u.name as name,\r\n" - + " u.usertype as usertype,\r\n" - + " b.reason as reason,\r\n" - + " b.start_date as start_date,\r\n" - + " b.end_date as end_date,\r\n" - + " b.no_of_days as no_of_days,\r\n" - + " b.booking_status as booking_status,\r\n" - + " b.amount_received as amount_received,\r\n" - + " COALESCE(rt.amount_refunded, 0) as amount_refunded,\r\n" - + " COALESCE(r.balace_amount, 0) as balance_amount\r\n" - + "FROM booking_details b\r\n" - + "JOIN hall_details h ON b.hall_details_hall_id = h.hall_id \r\n" - + "LEFT JOIN users u ON b.users_user_id = u.user_id\r\n" - + "LEFT JOIN refund_response r ON b.booking_id = r.booking_id\r\n" - + "LEFT JOIN refund_transaction rt ON b.booking_id = rt.booking_details_booking_id\r\n" - + "WHERE h.hall_id = :hallId AND b.booking_status != 'PENDING' ", nativeQuery = true) - List> getHallDetailsForOfficer( @Param("hallId") Integer hallIid); - - @Query(value ="SELECT bd.*, hd.hall_name, us.name, us.usertype "+ - "FROM booking_details bd "+ - "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id "+ - "JOIN users us ON bd.users_user_id = us.user_id "+ - "WHERE DATE(bd.booking_date) >= :fromDate "+ - "AND DATE(bd.booking_date) <= :toDate " + - "AND hd.zone = :zone ",nativeQuery=true) - List getAllBookingDetailsBookingDateByZone(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("zone") String zone); - - @Query(value ="SELECT bd.*, hd.hall_name, us.name, us.usertype "+ - "FROM booking_details bd "+ - "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id "+ - "JOIN users us ON bd.users_user_id = us.user_id "+ - "WHERE DATE(bd.start_date) >= :fromDate "+ - "AND DATE(bd.end_date) <= :toDate " + - "AND hd.zone = :zone ",nativeQuery=true) - List getAllBookingDetailsEventDateByZone(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("zone") String zone); - - @Query(value ="SELECT bd.*, hd.hall_name, us.name, us.usertype " + - "FROM booking_details bd " + - "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id "+ - "JOIN users us ON bd.users_user_id = us.user_id " + - "WHERE DATE(bd.booking_date) >= :fromDate " + - "AND DATE(bd.booking_date) <= :toDate " + - "AND hd.zone = :zone " + - "AND (:bookingStatus IS NULL OR bd.booking_status = :bookingStatus)",nativeQuery=true) - List getAllBookingDetailsBookingDateByZoneWithStatus(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("zone") String zone,@Param("bookingStatus") String bookingStatus); - - @Query(value ="SELECT bd.*, hd.hall_name, us.name, us.usertype " + - "FROM booking_details bd " + - "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id "+ - "JOIN users us ON bd.users_user_id = us.user_id " + - "WHERE DATE(bd.start_date) >= :fromDate " + - "AND DATE(bd.end_date) <= :toDate " + - "AND hd.zone = :zone " + - "AND (:bookingStatus IS NULL OR bd.booking_status = :bookingStatus)",nativeQuery=true) - List getAllBookingDetailsEventDateByZoneWithStatus(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("zone") String zone,@Param("bookingStatus") String bookingStatus); - -@Query(value ="SELECT bd.*, hd.hall_name, us.name, us.usertype " + - "FROM booking_details bd " + - "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + - "JOIN users us ON bd.users_user_id = us.user_id " + - "JOIN settlement st ON bd.booking_id=st.booking_details_booking_id " + - "WHERE DATE(bd.booking_date) >= :fromDate " + - "AND DATE(bd.booking_date) <= :toDate " + - "AND hd.zone = :zone ",nativeQuery=true) - List getAllBookingsettlementDetailsByZoneByBookingDate(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("zone") String zone); - - @Query(value ="SELECT bd.*, hd.hall_name, us.name, us.usertype " + - "FROM booking_details bd " + - "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + - "JOIN users us ON bd.users_user_id = us.user_id " + - "JOIN settlement st ON bd.booking_id=st.booking_details_booking_id " + - "WHERE DATE(bd.start_date) >= :fromDate " + - "AND DATE(bd.end_date) <= :toDate " + - "AND hd.zone = :zone ",nativeQuery=true) - List getAllBookingsettlementDetailsByZoneByEventDate(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("zone") String zone); - - @Query(value ="SELECT bd.*, hd.hall_name, us.name, us.usertype " + - "FROM booking_details bd " + - "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + - "JOIN users us ON bd.users_user_id = us.user_id " + - "JOIN settlement st ON bd.booking_id=st.booking_details_booking_id " + - "WHERE DATE(bd.booking_date) >= :fromDate " + - "AND DATE(bd.booking_date) <= :toDate " + - "AND hd.zone = :zone " + - "AND (:refundStatus IS NULL OR bd.refund_status = :refundStatus) ",nativeQuery=true) - List getAllBookingsettlementDetailsByZoneByBookingDateWithStatus(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("zone") String zone,@Param("refundStatus") String refundStatus); - - @Query(value ="SELECT bd.*, hd.hall_name, us.name, us.usertype " + - "FROM booking_details bd " + - "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + - "JOIN users us ON bd.users_user_id = us.user_id " + - "JOIN settlement st ON bd.booking_id=st.booking_details_booking_id " + - "WHERE DATE(bd.start_date) >= :fromDate " + - "AND DATE(bd.end_date) <= :toDate " + - "AND hd.zone = :zone " + - "AND (:refundStatus IS NULL OR bd.refund_status = :refundStatus) ",nativeQuery=true) - List getAllBookingsettlementDetailsByZoneByEventDateWithStatus(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("zone") String zone,@Param("refundStatus") String refundStatus); - -@Query(value ="SELECT bd.booking_id, bd.booking_date, hd.hall_name, us.name, us.usertype, p.transaction_id, p.payment_type, p.amount_received, bd.reason, bd.start_date, bd.end_date, p.payment_status " + - "FROM booking_details bd " + - "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + - "JOIN users us ON bd.users_user_id = us.user_id " + - "JOIN payments p ON bd.booking_id = p.booking_details_booking_id " + - "WHERE DATE(bd.booking_date) >= :fromDate " + - "AND DATE(bd.booking_date) <= :toDate " + - "AND hd.zone = :zone " + - "AND p.payment_status='Success' ",nativeQuery=true) - List getAllPaymentsDetailsByZone(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("zone") String zone); -@Query(value = "SELECT " + + + " b.booking_date as booking_date,\r\n" + + " u.name as name,\r\n" + + " u.usertype as usertype,\r\n" + + " b.reason as reason,\r\n" + + " b.start_date as start_date,\r\n" + + " b.end_date as end_date,\r\n" + + " b.no_of_days as no_of_days,\r\n" + + " b.booking_status as booking_status,\r\n" + + " b.amount_received as amount_received,\r\n" + + " COALESCE(rt.amount_refunded, 0) as amount_refunded,\r\n" + + " COALESCE(r.balace_amount, 0) as balance_amount\r\n" + + "FROM booking_details b\r\n" + + "JOIN hall_details h ON b.hall_details_hall_id = h.hall_id \r\n" + + "LEFT JOIN users u ON b.users_user_id = u.user_id\r\n" + + "LEFT JOIN refund_response r ON b.booking_id = r.booking_id\r\n" + + "LEFT JOIN refund_transaction rt ON b.booking_id = rt.booking_details_booking_id\r\n" + + "WHERE h.hall_id = :hallId AND b.booking_status != 'PENDING' ", nativeQuery = true) + List> getHallDetailsForOfficer(@Param("hallId") Integer hallIid); + + @Query(value = "SELECT bd.*, hd.hall_name, us.name, us.usertype " + + "FROM booking_details bd " + + "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + + "JOIN users us ON bd.users_user_id = us.user_id " + + "WHERE DATE(bd.booking_date) >= :fromDate " + + "AND DATE(bd.booking_date) <= :toDate " + + "AND hd.zone = :zone ", nativeQuery = true) + List getAllBookingDetailsBookingDateByZone(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("zone") String zone); + + @Query(value = "SELECT bd.*, hd.hall_name, us.name, us.usertype " + + "FROM booking_details bd " + + "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + + "JOIN users us ON bd.users_user_id = us.user_id " + + "WHERE DATE(bd.start_date) >= :fromDate " + + "AND DATE(bd.end_date) <= :toDate " + + "AND hd.zone = :zone ", nativeQuery = true) + List getAllBookingDetailsEventDateByZone(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("zone") String zone); + + @Query(value = "SELECT bd.*, hd.hall_name, us.name, us.usertype " + + "FROM booking_details bd " + + "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + + "JOIN users us ON bd.users_user_id = us.user_id " + + "WHERE DATE(bd.booking_date) >= :fromDate " + + "AND DATE(bd.booking_date) <= :toDate " + + "AND hd.zone = :zone " + + "AND (:bookingStatus IS NULL OR bd.booking_status = :bookingStatus)", nativeQuery = true) + List getAllBookingDetailsBookingDateByZoneWithStatus(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("zone") String zone, @Param("bookingStatus") String bookingStatus); + + @Query(value = "SELECT bd.*, hd.hall_name, us.name, us.usertype " + + "FROM booking_details bd " + + "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + + "JOIN users us ON bd.users_user_id = us.user_id " + + "WHERE DATE(bd.start_date) >= :fromDate " + + "AND DATE(bd.end_date) <= :toDate " + + "AND hd.zone = :zone " + + "AND (:bookingStatus IS NULL OR bd.booking_status = :bookingStatus)", nativeQuery = true) + List getAllBookingDetailsEventDateByZoneWithStatus(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("zone") String zone, @Param("bookingStatus") String bookingStatus); + + @Query(value = "SELECT bd.*, hd.hall_name, us.name, us.usertype " + + "FROM booking_details bd " + + "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + + "JOIN users us ON bd.users_user_id = us.user_id " + + "JOIN settlement st ON bd.booking_id=st.booking_details_booking_id " + + "WHERE DATE(bd.booking_date) >= :fromDate " + + "AND DATE(bd.booking_date) <= :toDate " + + "AND hd.zone = :zone ", nativeQuery = true) + List getAllBookingsettlementDetailsByZoneByBookingDate(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("zone") String zone); + + @Query(value = "SELECT bd.*, hd.hall_name, us.name, us.usertype " + + "FROM booking_details bd " + + "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + + "JOIN users us ON bd.users_user_id = us.user_id " + + "JOIN settlement st ON bd.booking_id=st.booking_details_booking_id " + + "WHERE DATE(bd.start_date) >= :fromDate " + + "AND DATE(bd.end_date) <= :toDate " + + "AND hd.zone = :zone ", nativeQuery = true) + List getAllBookingsettlementDetailsByZoneByEventDate(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("zone") String zone); + + @Query(value = "SELECT bd.*, hd.hall_name, us.name, us.usertype " + + "FROM booking_details bd " + + "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + + "JOIN users us ON bd.users_user_id = us.user_id " + + "JOIN settlement st ON bd.booking_id=st.booking_details_booking_id " + + "WHERE DATE(bd.booking_date) >= :fromDate " + + "AND DATE(bd.booking_date) <= :toDate " + + "AND hd.zone = :zone " + + "AND (:refundStatus IS NULL OR bd.refund_status = :refundStatus) ", nativeQuery = true) + List getAllBookingsettlementDetailsByZoneByBookingDateWithStatus(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("zone") String zone, @Param("refundStatus") String refundStatus); + + @Query(value = "SELECT bd.*, hd.hall_name, us.name, us.usertype " + + "FROM booking_details bd " + + "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + + "JOIN users us ON bd.users_user_id = us.user_id " + + "JOIN settlement st ON bd.booking_id=st.booking_details_booking_id " + + "WHERE DATE(bd.start_date) >= :fromDate " + + "AND DATE(bd.end_date) <= :toDate " + + "AND hd.zone = :zone " + + "AND (:refundStatus IS NULL OR bd.refund_status = :refundStatus) ", nativeQuery = true) + List getAllBookingsettlementDetailsByZoneByEventDateWithStatus(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("zone") String zone, @Param("refundStatus") String refundStatus); + + @Query(value = "SELECT bd.booking_id, bd.booking_date, hd.hall_name, us.name, us.usertype, p.transaction_id, p.payment_type, p.amount_received, bd.reason, bd.start_date, bd.end_date, p.payment_status " + + "FROM booking_details bd " + + "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + + "JOIN users us ON bd.users_user_id = us.user_id " + + "JOIN payments p ON bd.booking_id = p.booking_details_booking_id " + + "WHERE DATE(bd.booking_date) >= :fromDate " + + "AND DATE(bd.booking_date) <= :toDate " + + "AND hd.zone = :zone " + + "AND p.payment_status='Success' ", nativeQuery = true) + List getAllPaymentsDetailsByZone(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("zone") String zone); + + @Query(value = "SELECT " + "h.hall_name AS HallName, " + "h.zone AS Zone, " + "h.division AS Division, " + - "CONCAT(h.door_no,',',h.street, ', ', h.area, ', ', h.city, ', ', h.pin_code) AS Address, " + - "COUNT(*) AS HallTotalBookings, " + + "CONCAT(h.door_no,',',h.street, ', ', h.area, ', ', h.city, ', ', h.pin_code) AS Address, " + + "COUNT(*) AS HallTotalBookings, " + "SUM(p.amount_received) AS AmountReceived, " + - "COALESCE(SUM(r.amount_refunded), 0) AS AmountRefund, " + //Use COALESCE to handle NULL values + "COALESCE(SUM(r.amount_refunded), 0) AS AmountRefund, " + //Use COALESCE to handle NULL values "(SUM(p.amount_received) - COALESCE(SUM(r.amount_refunded), 0)) AS Difference " + // Calculate the difference "FROM " + "booking_details bd " + @@ -1038,25 +1047,24 @@ List findPastEventsByHallId(@Param("hallId") Integer hallId); "hall_details h ON bd.hall_details_hall_id = h.hall_id " + "JOIN " + "payments p ON bd.booking_id = p.booking_details_booking_id " + - "LEFT JOIN " + + "LEFT JOIN " + "refund_transaction r ON p.transaction_id = r.transaction_id " + - "WHERE DATE(bd.booking_date) >= :fromDate "+ + "WHERE DATE(bd.booking_date) >= :fromDate " + "AND DATE(bd.booking_date) <= :toDate " + "AND h.zone = :zone " + "GROUP BY " + "h.hall_id", nativeQuery = true) List getBookingHallDetailsReportByZoneByBookingDate(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("zone") String zone); - - - + + @Query(value = "SELECT " + "h.hall_name AS HallName, " + "h.zone AS Zone, " + "h.division AS Division, " + - "CONCAT(h.door_no,',',h.street, ', ', h.area, ', ', h.city, ', ', h.pin_code) AS Address, " + - "COUNT(*) AS HallTotalBookings, " + + "CONCAT(h.door_no,',',h.street, ', ', h.area, ', ', h.city, ', ', h.pin_code) AS Address, " + + "COUNT(*) AS HallTotalBookings, " + "SUM(p.amount_received) AS AmountReceived, " + - "COALESCE(SUM(r.amount_refunded), 0) AS AmountRefund, " + //Use COALESCE to handle NULL values + "COALESCE(SUM(r.amount_refunded), 0) AS AmountRefund, " + //Use COALESCE to handle NULL values "(SUM(p.amount_received) - COALESCE(SUM(r.amount_refunded), 0)) AS Difference " + // Calculate the difference "FROM " + "booking_details bd " + @@ -1064,9 +1072,9 @@ List findPastEventsByHallId(@Param("hallId") Integer hallId); "hall_details h ON bd.hall_details_hall_id = h.hall_id " + "JOIN " + "payments p ON bd.booking_id = p.booking_details_booking_id " + - "LEFT JOIN " + + "LEFT JOIN " + "refund_transaction r ON p.transaction_id = r.transaction_id " + - "WHERE DATE(bd.start_date) >= :fromDate "+ + "WHERE DATE(bd.start_date) >= :fromDate " + "AND DATE(bd.end_date) <= :toDate " + "AND h.zone = :zone " + "GROUP BY " + @@ -1077,10 +1085,10 @@ List findPastEventsByHallId(@Param("hallId") Integer hallId); "h.hall_name AS HallName, " + "h.zone AS Zone, " + "h.division AS Division, " + - "CONCAT(h.door_no,',',h.street, ', ', h.area, ', ', h.city, ', ', h.pin_code) AS Address, " + - "COUNT(*) AS HallTotalBookings, " + + "CONCAT(h.door_no,',',h.street, ', ', h.area, ', ', h.city, ', ', h.pin_code) AS Address, " + + "COUNT(*) AS HallTotalBookings, " + "SUM(p.amount_received) AS AmountReceived, " + - "COALESCE(SUM(r.amount_refunded), 0) AS AmountRefund, " + //Use COALESCE to handle NULL values + "COALESCE(SUM(r.amount_refunded), 0) AS AmountRefund, " + //Use COALESCE to handle NULL values "(SUM(p.amount_received) - COALESCE(SUM(r.amount_refunded), 0)) AS Difference " + // Calculate the difference "FROM " + "booking_details bd " + @@ -1088,25 +1096,25 @@ List findPastEventsByHallId(@Param("hallId") Integer hallId); "hall_details h ON bd.hall_details_hall_id = h.hall_id " + "JOIN " + "payments p ON bd.booking_id = p.booking_details_booking_id " + - "LEFT JOIN " + + "LEFT JOIN " + "refund_transaction r ON p.transaction_id = r.transaction_id " + - "WHERE DATE(bd.booking_date) >= :fromDate "+ + "WHERE DATE(bd.booking_date) >= :fromDate " + "AND DATE(bd.booking_date) <= :toDate " + "AND h.zone = :zone " + "AND (:hall_id = '0' OR h.hall_id = :hall_id) " + "GROUP BY " + "h.hall_id", nativeQuery = true) - List getBookingHallDetailsReportByZoneByBookingDateHallname(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("zone") String zone,@Param("hall_id") Integer hallId); - - + List getBookingHallDetailsReportByZoneByBookingDateHallname(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("zone") String zone, @Param("hall_id") Integer hallId); + + @Query(value = "SELECT " + "h.hall_name AS HallName, " + "h.zone AS Zone, " + "h.division AS Division, " + - "CONCAT(h.door_no,',',h.street, ', ', h.area, ', ', h.city, ', ', h.pin_code) AS Address, " + - "COUNT(*) AS HallTotalBookings, " + + "CONCAT(h.door_no,',',h.street, ', ', h.area, ', ', h.city, ', ', h.pin_code) AS Address, " + + "COUNT(*) AS HallTotalBookings, " + "SUM(p.amount_received) AS AmountReceived, " + - "COALESCE(SUM(r.amount_refunded), 0) AS AmountRefund, " + //Use COALESCE to handle NULL values + "COALESCE(SUM(r.amount_refunded), 0) AS AmountRefund, " + //Use COALESCE to handle NULL values "(SUM(p.amount_received) - COALESCE(SUM(r.amount_refunded), 0)) AS Difference " + // Calculate the difference "FROM " + "booking_details bd " + @@ -1114,21 +1122,21 @@ List findPastEventsByHallId(@Param("hallId") Integer hallId); "hall_details h ON bd.hall_details_hall_id = h.hall_id " + "JOIN " + "payments p ON bd.booking_id = p.booking_details_booking_id " + - "LEFT JOIN " + + "LEFT JOIN " + "refund_transaction r ON p.transaction_id = r.transaction_id " + - "WHERE DATE(bd.start_date) >= :fromDate "+ + "WHERE DATE(bd.start_date) >= :fromDate " + "AND DATE(bd.end_date) <= :toDate " + "AND h.zone = :zone " + "AND (:hall_id = '0' OR h.hall_id = :hall_id) " + "GROUP BY " + "h.hall_id", nativeQuery = true) - List getBookingHallDetailsReportByZoneByEventDateHallname(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("zone") String zone,@Param("hall_id") Integer hallId); - - // Present Events: Fetch today's events + List getBookingHallDetailsReportByZoneByEventDateHallname(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("zone") String zone, @Param("hall_id") Integer hallId); + + // Present Events: Fetch today's events @Query(value = "SELECT * FROM booking_details WHERE DATE(start_date) = CURRENT_DATE() AND booking_status='APPROVED'", nativeQuery = true) List findPresentBookingList(); - // Past Events: Fetch events + // Past Events: Fetch events @Query(value = "SELECT * FROM booking_details " + "WHERE DATE(start_date) < CURRENT_DATE() " + "AND booking_status='APPROVED'", nativeQuery = true) @@ -1138,274 +1146,290 @@ List findPastEventsByHallId(@Param("hallId") Integer hallId); @Query(value = "SELECT * FROM booking_details " + "WHERE start_date BETWEEN CURDATE() + INTERVAL 1 DAY AND CURDATE() + INTERVAL 2 DAY " + "AND booking_status = 'APPROVED'", nativeQuery = true) -List findFutureEventsList(); - - //admin reports + List findFutureEventsList(); + + //admin reports + @Query(value = "SELECT bd.booking_id, bd.booking_date, hd.hall_name, us.name, us.mobile_no, " + + "CONCAT(us.doorno, ', ', us.street, ', ', us.area, ', ', us.location, ', ', us.pin_code) AS address, " + + "us.usertype, bd.reason, bd.start_date, bd.end_date, " + + "bd.deposit_amount, bd.hall_amount, bd.gst, bd.amount_received, bd.booking_status " + + "FROM booking_details bd " + + "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + + "JOIN users us ON bd.users_user_id = us.user_id " + + "WHERE DATE(bd.booking_date) >= :fromDate " + + "AND DATE(bd.booking_date) <= :toDate " + + "AND (:zone IS NULL OR :zone = 'ALL' OR hd.zone = :zone) " + + "AND (:division IS NULL OR :division = 'ALL' OR hd.division = :division) " + + "AND (:hallid IS NULL OR :hallid = '1000' OR hd.hall_id = :hallid) " + + "AND bd.booking_status!='PENDING' ", nativeQuery = true) + List getBookingDetailsByBookingDate(@Param("fromDate") String fromDate, + @Param("toDate") String toDate, @Param("zone") String zone, @Param("division") String division, @Param("hallid") Integer hallid); + + @Query(value = "SELECT bd.booking_id, bd.booking_date, hd.hall_name, us.name, us.mobile_no, " + + "CONCAT(us.doorno, ', ', us.street, ', ', us.area, ', ', us.location, ', ', us.pin_code) AS address, " + + "us.usertype, bd.reason, bd.start_date, bd.end_date, " + + "bd.deposit_amount, bd.hall_amount, bd.gst, bd.amount_received, bd.booking_status " + + "FROM booking_details bd " + + "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + + "JOIN users us ON bd.users_user_id = us.user_id " + + "WHERE DATE(bd.booking_date) >= :fromDate " + + "AND DATE(bd.booking_date) <= :toDate " + + "AND (:zone IS NULL OR :zone = 'ALL' OR hd.zone = :zone) " + + "AND (:division IS NULL OR :division = 'ALL' OR hd.division = :division) " + + "AND (:hallid IS NULL OR :hallid = '1000' OR hd.hall_id = :hallid) " + + "AND bd.booking_status = :bookingStatus ", nativeQuery = true) + List getBookingDetailsByBookingDateWithStatus(@Param("fromDate") String fromDate, + @Param("toDate") String toDate, + @Param("bookingStatus") String bookingStatus, @Param("zone") String zone, @Param("division") String division, @Param("hallid") Integer hallid); + + + @Query(value = "SELECT bd.booking_id, bd.booking_date, hd.hall_name, us.name, us.mobile_no, " + + "CONCAT(us.doorno, ', ', us.street, ', ', us.area, ', ', us.location, ', ', us.pin_code) AS address, " + + "us.usertype, bd.reason, bd.start_date, bd.end_date, " + + "bd.deposit_amount, bd.hall_amount, bd.gst, bd.amount_received, bd.booking_status " + + "FROM booking_details bd " + + "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + + "JOIN users us ON bd.users_user_id = us.user_id " + + "WHERE DATE(bd.start_date) >= :fromDate " + + "AND DATE(bd.end_date) <= :toDate " + + "AND (:zone IS NULL OR :zone = 'ALL' OR hd.zone = :zone) " + + "AND (:division IS NULL OR :division = 'ALL' OR hd.division = :division) " + + "AND (:hallid IS NULL OR :hallid = '1000' OR hd.hall_id = :hallid) " + + "AND bd.booking_status!='PENDING' ", nativeQuery = true) + List getBookingDetailsByEventDate(@Param("fromDate") String fromDate, + @Param("toDate") String toDate, @Param("zone") String zone, @Param("division") String division, @Param("hallid") Integer hallid); + @Query(value = "SELECT bd.booking_id, bd.booking_date, hd.hall_name, us.name, us.mobile_no, " + - "CONCAT(us.doorno, ', ', us.street, ', ', us.area, ', ', us.location, ', ', us.pin_code) AS address, " + - "us.usertype, bd.reason, bd.start_date, bd.end_date, " + - "bd.deposit_amount, bd.hall_amount, bd.gst, bd.amount_received, bd.booking_status " + - "FROM booking_details bd " + - "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + - "JOIN users us ON bd.users_user_id = us.user_id " + - "WHERE DATE(bd.booking_date) >= :fromDate " + - "AND DATE(bd.booking_date) <= :toDate "+ - "AND (:zone IS NULL OR :zone = 'ALL' OR hd.zone = :zone) " + - "AND (:division IS NULL OR :division = 'ALL' OR hd.division = :division) " + - "AND (:hallid IS NULL OR :hallid = '1000' OR hd.hall_id = :hallid) " + - "AND bd.booking_status!='PENDING' ",nativeQuery = true) - List getBookingDetailsByBookingDate(@Param("fromDate") String fromDate, - @Param("toDate") String toDate,@Param("zone") String zone,@Param("division") String division,@Param("hallid") Integer hallid); - - @Query(value = "SELECT bd.booking_id, bd.booking_date, hd.hall_name, us.name, us.mobile_no, " + - "CONCAT(us.doorno, ', ', us.street, ', ', us.area, ', ', us.location, ', ', us.pin_code) AS address, " + - "us.usertype, bd.reason, bd.start_date, bd.end_date, " + - "bd.deposit_amount, bd.hall_amount, bd.gst, bd.amount_received, bd.booking_status " + - "FROM booking_details bd " + - "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + - "JOIN users us ON bd.users_user_id = us.user_id " + - "WHERE DATE(bd.booking_date) >= :fromDate " + - "AND DATE(bd.booking_date) <= :toDate " + - "AND (:zone IS NULL OR :zone = 'ALL' OR hd.zone = :zone) " + - "AND (:division IS NULL OR :division = 'ALL' OR hd.division = :division) " + - "AND (:hallid IS NULL OR :hallid = '1000' OR hd.hall_id = :hallid) " + - "AND bd.booking_status = :bookingStatus ",nativeQuery = true) - List getBookingDetailsByBookingDateWithStatus(@Param("fromDate") String fromDate, - @Param("toDate") String toDate, - @Param("bookingStatus") String bookingStatus,@Param("zone") String zone,@Param("division") String division,@Param("hallid") Integer hallid); - - - @Query(value = "SELECT bd.booking_id, bd.booking_date, hd.hall_name, us.name, us.mobile_no, " + - "CONCAT(us.doorno, ', ', us.street, ', ', us.area, ', ', us.location, ', ', us.pin_code) AS address, " + - "us.usertype, bd.reason, bd.start_date, bd.end_date, " + - "bd.deposit_amount, bd.hall_amount, bd.gst, bd.amount_received, bd.booking_status " + - "FROM booking_details bd " + - "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + - "JOIN users us ON bd.users_user_id = us.user_id " + - "WHERE DATE(bd.start_date) >= :fromDate " + - "AND DATE(bd.end_date) <= :toDate " + - "AND (:zone IS NULL OR :zone = 'ALL' OR hd.zone = :zone) " + - "AND (:division IS NULL OR :division = 'ALL' OR hd.division = :division) " + - "AND (:hallid IS NULL OR :hallid = '1000' OR hd.hall_id = :hallid) " + - "AND bd.booking_status!='PENDING' ",nativeQuery = true) - List getBookingDetailsByEventDate(@Param("fromDate") String fromDate, - @Param("toDate") String toDate,@Param("zone") String zone,@Param("division") String division,@Param("hallid") Integer hallid); - - @Query(value = "SELECT bd.booking_id, bd.booking_date, hd.hall_name, us.name, us.mobile_no, " + - "CONCAT(us.doorno, ', ', us.street, ', ', us.area, ', ', us.location, ', ', us.pin_code) AS address, " + - "us.usertype, bd.reason, bd.start_date, bd.end_date, " + - "bd.deposit_amount, bd.hall_amount, bd.gst, bd.amount_received, bd.booking_status " + - "FROM booking_details bd " + - "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + - "JOIN users us ON bd.users_user_id = us.user_id " + - "WHERE DATE(bd.start_date) >= :fromDate " + - "AND DATE(bd.end_date) <= :toDate " + - "AND (:zone IS NULL OR :zone = 'ALL' OR hd.zone = :zone) " + - "AND (:division IS NULL OR :division = 'ALL' OR hd.division = :division) " + - "AND (:hallid IS NULL OR :hallid = '1000' OR hd.hall_id = :hallid) " + - "AND bd.booking_status = :bookingStatus",nativeQuery = true) - List getBookingDetailsByEventDateWithStatus(@Param("fromDate") String fromDate, - @Param("toDate") String toDate, - @Param("bookingStatus") String bookingStatus,@Param("zone") String zone,@Param("division") String division,@Param("hallid") Integer hallid); - - @Query(value = "SELECT bd.booking_id, bd.booking_date, hd.hall_name, us.name, us.usertype, p.transaction_id, p.payment_type, bd.deposit_amount, bd.hall_amount, bd.gst, p.amount_received, bd.reason, bd.start_date, bd.end_date, p.payment_status " + - "FROM booking_details bd " + - "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + - "JOIN users us ON bd.users_user_id = us.user_id " + - "JOIN payments p ON bd.booking_id = p.booking_details_booking_id " + - "WHERE DATE(p.cdate) >= :fromDate " + - "AND DATE(p.cdate) <= :toDate " + - "AND (:paymentStatus IS NULL OR p.payment_status = :paymentStatus)" + - "AND (:zone IS NULL OR :zone = 'ALL' OR hd.zone = :zone) " + - "AND (:division IS NULL OR :division = 'ALL' OR hd.division = :division) " + - "AND (:hallid IS NULL OR :hallid = '1000' OR hd.hall_id = :hallid) ", - nativeQuery = true) - List getAllPaymentsDetails(@Param("fromDate") String fromDate, @Param("toDate") String toDate,@Param("paymentStatus") String paymentStatus,@Param("zone") String zone,@Param("division") String division,@Param("hallid") Integer hallid); - - @Query(value = "SELECT bd.booking_id, bd.booking_date, hd.hall_name, us.name, us.usertype, p.transaction_id, p.payment_type, bd.deposit_amount, bd.hall_amount, bd.gst, p.amount_received, bd.reason, bd.start_date, bd.end_date, p.payment_status " + - "FROM booking_details bd " + - "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + - "JOIN users us ON bd.users_user_id = us.user_id " + - "JOIN extra_payments p ON bd.booking_id = p.booking_details_booking_id " + - "WHERE DATE(p.cdate) >= :fromDate " + - "AND DATE(p.cdate) <= :toDate " + - "AND (:paymentStatus IS NULL OR p.payment_status = :paymentStatus)" + - "AND (:zone IS NULL OR :zone = 'ALL' OR hd.zone = :zone) " + - "AND (:division IS NULL OR :division = 'ALL' OR hd.division = :division) " + - "AND (:hallid IS NULL OR :hallid = '1000' OR hd.hall_id = :hallid) ", - nativeQuery = true) - List getAllExtraPaymentsDetails(@Param("fromDate") String fromDate, @Param("toDate") String toDate,@Param("paymentStatus") String paymentStatus,@Param("zone") String zone,@Param("division") String division,@Param("hallid") Integer hallid); - - - @Query(value = "SELECT " + - "h.hall_name AS HallName, " + - "h.hall_Incharge_name AS InchargeName, " + - "h.hall_Incharge_no AS hallInchargeMobno, " + - "CONCAT(h.zone, '/', h.division) AS ZoneDivision, " + // Concatenate zone and division - "COUNT(*) AS HallTotalBookings, " + - "SUM(bd.deposit_amount) AS depositAmount, " + - "SUM(bd.hall_amount) AS hallAmount, " + - "SUM(bd.gst) AS gst, " + - "SUM(p.amount_received) AS AmountReceived, " + - "COALESCE(SUM(r.amount - r.balace_amount), 0) AS AmountRefund, " + - "COALESCE(SUM(CASE WHEN bd.booking_status IN ('COMPLETED', 'CANCELED') THEN r.balace_amount - bd.gst ELSE 0 END), 0) AS NetRevenue " + - "FROM " + - "booking_details bd " + - "JOIN " + - "hall_details h ON bd.hall_details_hall_id = h.hall_id " + - "JOIN " + - "payments p ON bd.booking_id = p.booking_details_booking_id " + - "LEFT JOIN refund_response r ON bd.booking_id = r.booking_id " + - "WHERE DATE(bd.booking_date) >= :fromDate " + - "AND DATE(bd.booking_date) <= :toDate " + - "AND (:zone IS NULL OR :zone = 'ALL' OR h.zone = :zone) " + - "AND (:division IS NULL OR :division = 'ALL' OR h.division = :division) " + - "AND (:hallid IS NULL OR :hallid = '1000' OR h.hall_id = :hallid) " + - "GROUP BY " + - "bd.hall_details_hall_id", nativeQuery = true) - List getBookingHallDetailsReportByBookingDate(@Param("fromDate") String fromDate, @Param("toDate") String toDate,@Param("zone") String zone,@Param("division") String division,@Param("hallid") Integer hallid); - - - @Query(value = "SELECT " + - "h.hall_name AS HallName, " + - "h.hall_Incharge_name AS InchargeName, " + - "h.hall_Incharge_no AS hallInchargeMobno, " + - "CONCAT(h.zone, '/', h.division) AS ZoneDivision, " + // Concatenate zone and division - "COUNT(*) AS HallTotalBookings, " + - "SUM(bd.deposit_amount) AS depositAmount, " + - "SUM(bd.hall_amount) AS hallAmount, " + - "SUM(bd.gst) AS gst, " + - "SUM(p.amount_received) AS AmountReceived, " + - "COALESCE(SUM(r.amount - r.balace_amount), 0) AS AmountRefund, " + - "COALESCE(SUM(CASE WHEN bd.booking_status IN ('COMPLETED', 'CANCELED') THEN r.balace_amount - bd.gst ELSE 0 END), 0) AS NetRevenue " + - "FROM " + - "booking_details bd " + - "JOIN " + - "hall_details h ON bd.hall_details_hall_id = h.hall_id " + - "JOIN " + - "payments p ON bd.booking_id = p.booking_details_booking_id " + - "LEFT JOIN refund_response r ON bd.booking_id = r.booking_id " + - "WHERE DATE(bd.start_date) >= :fromDate " + - "AND DATE(bd.end_date) <= :toDate " + - "AND (:zone IS NULL OR :zone = 'ALL' OR h.zone = :zone) " + - "AND (:division IS NULL OR :division = 'ALL' OR h.division = :division) " + - "AND (:hallid IS NULL OR :hallid = '1000' OR h.hall_id = :hallid) " + - "GROUP BY " + - "bd.hall_details_hall_id", nativeQuery = true) - List getBookingHallDetailsReportByEventDate(@Param("fromDate") String fromDate, @Param("toDate") String toDate,@Param("zone") String zone,@Param("division") String division,@Param("hallid") Integer hallid); - - - @Query(value ="SELECT bd.*, hd.hall_name, us.name, us.usertype " + - "FROM booking_details bd " + - "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + - "JOIN users us ON bd.users_user_id = us.user_id " + - "left JOIN settlement st ON bd.booking_id=st.booking_details_booking_id " + - "WHERE DATE(bd.booking_date) >= :fromDate " + - "AND DATE(bd.booking_date) <= :toDate ",nativeQuery=true) - List getAllBookingsettlementDetailsByBookingDate(@Param("fromDate") String fromDate, @Param("toDate") String toDate); - - @Query(value ="SELECT bd.*, hd.hall_name, us.name, us.usertype " + - "FROM booking_details bd " + - "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + - "JOIN users us ON bd.users_user_id = us.user_id " + - "left JOIN settlement st ON bd.booking_id=st.booking_details_booking_id " + - "WHERE DATE(bd.booking_date) >= :fromDate " + - "AND DATE(bd.booking_date) <= :toDate " + - "AND (:refundStatus IS NULL OR bd.refund_status = :refundStatus) ",nativeQuery=true) - List getAllBookingsettlementDetailsByBookingDateWithStatus(@Param("fromDate") String fromDate, @Param("toDate") String toDate,@Param("refundStatus") String refundStatus); - - @Query(value ="SELECT bd.*, hd.hall_name, us.name, us.usertype " + - "FROM booking_details bd " + - "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + - "JOIN users us ON bd.users_user_id = us.user_id " + - "left JOIN settlement st ON bd.booking_id=st.booking_details_booking_id " + - "WHERE DATE(bd.start_date) >= :fromDate " + - "AND DATE(bd.end_date) <= :toDate ",nativeQuery=true) - List getAllBookingsettlementDetailsByEventDate(@Param("fromDate") String fromDate, @Param("toDate") String toDate); - - @Query(value ="SELECT bd.*, hd.hall_name, us.name, us.usertype " + - "FROM booking_details bd " + - "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + - "JOIN users us ON bd.users_user_id = us.user_id " + - "left JOIN settlement st ON bd.booking_id=st.booking_details_booking_id " + - "WHERE DATE(bd.start_date) >= :fromDate " + - "AND DATE(bd.end_date) <= :toDate " + - "AND (:refundStatus IS NULL OR bd.refund_status = :refundStatus) ",nativeQuery=true) - List getAllBookingsettlementDetailsByEventDateWithStatus(@Param("fromDate") String fromDate, @Param("toDate") String toDate,@Param("refundStatus") String refundStatus); - // In BookingDetailsRepository.java - // In BookingDetailsRepository.java - @Query("SELECT h.zone, COUNT(b) FROM BookingDetails b JOIN b.hallDetails h WHERE b.bookingStatus = 'APPROVED' GROUP BY h.zone") - List countBookingsByZone(); - - @Query("SELECT h.division, COUNT(b) FROM BookingDetails b JOIN b.hallDetails h WHERE b.bookingStatus = 'APPROVED' GROUP BY h.division") - List countBookingsByDivisions(); - - @Query("SELECT b FROM BookingDetails b JOIN b.hallDetails h WHERE h.zone = :zone AND b.bookingStatus = 'APPROVED'") + "CONCAT(us.doorno, ', ', us.street, ', ', us.area, ', ', us.location, ', ', us.pin_code) AS address, " + + "us.usertype, bd.reason, bd.start_date, bd.end_date, " + + "bd.deposit_amount, bd.hall_amount, bd.gst, bd.amount_received, bd.booking_status " + + "FROM booking_details bd " + + "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + + "JOIN users us ON bd.users_user_id = us.user_id " + + "WHERE DATE(bd.start_date) >= :fromDate " + + "AND DATE(bd.end_date) <= :toDate " + + "AND (:zone IS NULL OR :zone = 'ALL' OR hd.zone = :zone) " + + "AND (:division IS NULL OR :division = 'ALL' OR hd.division = :division) " + + "AND (:hallid IS NULL OR :hallid = '1000' OR hd.hall_id = :hallid) " + + "AND bd.booking_status = :bookingStatus", nativeQuery = true) + List getBookingDetailsByEventDateWithStatus(@Param("fromDate") String fromDate, + @Param("toDate") String toDate, + @Param("bookingStatus") String bookingStatus, @Param("zone") String zone, @Param("division") String division, @Param("hallid") Integer hallid); + + @Query(value = "SELECT bd.booking_id, bd.booking_date, hd.hall_name, us.name, us.usertype, p.transaction_id, p.payment_type, bd.deposit_amount, bd.hall_amount, bd.gst, p.amount_received, bd.reason, bd.start_date, bd.end_date, p.payment_status " + + "FROM booking_details bd " + + "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + + "JOIN users us ON bd.users_user_id = us.user_id " + + "JOIN payments p ON bd.booking_id = p.booking_details_booking_id " + + "WHERE DATE(p.cdate) >= :fromDate " + + "AND DATE(p.cdate) <= :toDate " + + "AND (:paymentStatus IS NULL OR p.payment_status = :paymentStatus)" + + "AND (:zone IS NULL OR :zone = 'ALL' OR hd.zone = :zone) " + + "AND (:division IS NULL OR :division = 'ALL' OR hd.division = :division) " + + "AND (:hallid IS NULL OR :hallid = '1000' OR hd.hall_id = :hallid) ", + nativeQuery = true) + List getAllPaymentsDetails(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("paymentStatus") String paymentStatus, @Param("zone") String zone, @Param("division") String division, @Param("hallid") Integer hallid); + + @Query(value = "SELECT bd.booking_id, bd.booking_date, hd.hall_name, us.name, us.usertype, p.transaction_id, p.payment_type, bd.deposit_amount, bd.hall_amount, bd.gst, p.amount_received, bd.reason, bd.start_date, bd.end_date, p.payment_status " + + "FROM booking_details bd " + + "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + + "JOIN users us ON bd.users_user_id = us.user_id " + + "JOIN extra_payments p ON bd.booking_id = p.booking_details_booking_id " + + "WHERE DATE(p.cdate) >= :fromDate " + + "AND DATE(p.cdate) <= :toDate " + + "AND (:paymentStatus IS NULL OR p.payment_status = :paymentStatus)" + + "AND (:zone IS NULL OR :zone = 'ALL' OR hd.zone = :zone) " + + "AND (:division IS NULL OR :division = 'ALL' OR hd.division = :division) " + + "AND (:hallid IS NULL OR :hallid = '1000' OR hd.hall_id = :hallid) ", + nativeQuery = true) + List getAllExtraPaymentsDetails(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("paymentStatus") String paymentStatus, @Param("zone") String zone, @Param("division") String division, @Param("hallid") Integer hallid); + + + @Query(value = "SELECT " + + "h.hall_name AS HallName, " + + "h.hall_Incharge_name AS InchargeName, " + + "h.hall_Incharge_no AS hallInchargeMobno, " + + "CONCAT(h.zone, '/', h.division) AS ZoneDivision, " + // Concatenate zone and division + "COUNT(*) AS HallTotalBookings, " + + "SUM(bd.deposit_amount) AS depositAmount, " + + "SUM(bd.hall_amount) AS hallAmount, " + + "SUM(bd.gst) AS gst, " + + "SUM(p.amount_received) AS AmountReceived, " + + "COALESCE(SUM(r.amount - r.balace_amount), 0) AS AmountRefund, " + + "COALESCE(SUM(CASE WHEN bd.booking_status IN ('COMPLETED', 'CANCELED') THEN r.balace_amount - bd.gst ELSE 0 END), 0) AS NetRevenue " + + "FROM " + + "booking_details bd " + + "JOIN " + + "hall_details h ON bd.hall_details_hall_id = h.hall_id " + + "JOIN " + + "payments p ON bd.booking_id = p.booking_details_booking_id " + + "LEFT JOIN refund_response r ON bd.booking_id = r.booking_id " + + "WHERE DATE(bd.booking_date) >= :fromDate " + + "AND DATE(bd.booking_date) <= :toDate " + + "AND (:zone IS NULL OR :zone = 'ALL' OR h.zone = :zone) " + + "AND (:division IS NULL OR :division = 'ALL' OR h.division = :division) " + + "AND (:hallid IS NULL OR :hallid = '1000' OR h.hall_id = :hallid) " + + "GROUP BY " + + "bd.hall_details_hall_id", nativeQuery = true) + List getBookingHallDetailsReportByBookingDate(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("zone") String zone, @Param("division") String division, @Param("hallid") Integer hallid); + + + @Query(value = "SELECT " + + "h.hall_name AS HallName, " + + "h.hall_Incharge_name AS InchargeName, " + + "h.hall_Incharge_no AS hallInchargeMobno, " + + "CONCAT(h.zone, '/', h.division) AS ZoneDivision, " + // Concatenate zone and division + "COUNT(*) AS HallTotalBookings, " + + "SUM(bd.deposit_amount) AS depositAmount, " + + "SUM(bd.hall_amount) AS hallAmount, " + + "SUM(bd.gst) AS gst, " + + "SUM(p.amount_received) AS AmountReceived, " + + "COALESCE(SUM(r.amount - r.balace_amount), 0) AS AmountRefund, " + + "COALESCE(SUM(CASE WHEN bd.booking_status IN ('COMPLETED', 'CANCELED') THEN r.balace_amount - bd.gst ELSE 0 END), 0) AS NetRevenue " + + "FROM " + + "booking_details bd " + + "JOIN " + + "hall_details h ON bd.hall_details_hall_id = h.hall_id " + + "JOIN " + + "payments p ON bd.booking_id = p.booking_details_booking_id " + + "LEFT JOIN refund_response r ON bd.booking_id = r.booking_id " + + "WHERE DATE(bd.start_date) >= :fromDate " + + "AND DATE(bd.end_date) <= :toDate " + + "AND (:zone IS NULL OR :zone = 'ALL' OR h.zone = :zone) " + + "AND (:division IS NULL OR :division = 'ALL' OR h.division = :division) " + + "AND (:hallid IS NULL OR :hallid = '1000' OR h.hall_id = :hallid) " + + "GROUP BY " + + "bd.hall_details_hall_id", nativeQuery = true) + List getBookingHallDetailsReportByEventDate(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("zone") String zone, @Param("division") String division, @Param("hallid") Integer hallid); + + + @Query(value = "SELECT bd.*, hd.hall_name, us.name, us.usertype " + + "FROM booking_details bd " + + "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + + "JOIN users us ON bd.users_user_id = us.user_id " + + "left JOIN settlement st ON bd.booking_id=st.booking_details_booking_id " + + "WHERE DATE(bd.booking_date) >= :fromDate " + + "AND DATE(bd.booking_date) <= :toDate ", nativeQuery = true) + List getAllBookingsettlementDetailsByBookingDate(@Param("fromDate") String fromDate, @Param("toDate") String toDate); + + @Query(value = "SELECT bd.*, hd.hall_name, us.name, us.usertype " + + "FROM booking_details bd " + + "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + + "JOIN users us ON bd.users_user_id = us.user_id " + + "left JOIN settlement st ON bd.booking_id=st.booking_details_booking_id " + + "WHERE DATE(bd.booking_date) >= :fromDate " + + "AND DATE(bd.booking_date) <= :toDate " + + "AND (:refundStatus IS NULL OR bd.refund_status = :refundStatus) ", nativeQuery = true) + List getAllBookingsettlementDetailsByBookingDateWithStatus(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("refundStatus") String refundStatus); + + @Query(value = "SELECT bd.*, hd.hall_name, us.name, us.usertype " + + "FROM booking_details bd " + + "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + + "JOIN users us ON bd.users_user_id = us.user_id " + + "left JOIN settlement st ON bd.booking_id=st.booking_details_booking_id " + + "WHERE DATE(bd.start_date) >= :fromDate " + + "AND DATE(bd.end_date) <= :toDate ", nativeQuery = true) + List getAllBookingsettlementDetailsByEventDate(@Param("fromDate") String fromDate, @Param("toDate") String toDate); + + @Query(value = "SELECT bd.*, hd.hall_name, us.name, us.usertype " + + "FROM booking_details bd " + + "JOIN hall_details hd ON bd.hall_details_hall_id = hd.hall_id " + + "JOIN users us ON bd.users_user_id = us.user_id " + + "left JOIN settlement st ON bd.booking_id=st.booking_details_booking_id " + + "WHERE DATE(bd.start_date) >= :fromDate " + + "AND DATE(bd.end_date) <= :toDate " + + "AND (:refundStatus IS NULL OR bd.refund_status = :refundStatus) ", nativeQuery = true) + List getAllBookingsettlementDetailsByEventDateWithStatus(@Param("fromDate") String fromDate, @Param("toDate") String toDate, @Param("refundStatus") String refundStatus); + + // In BookingDetailsRepository.java + // In BookingDetailsRepository.java + @Query("SELECT h.zone, COUNT(b) FROM BookingDetails b JOIN b.hallDetails h WHERE b.bookingStatus = 'APPROVED' GROUP BY h.zone") + List countBookingsByZone(); + + @Query("SELECT h.division, COUNT(b) FROM BookingDetails b JOIN b.hallDetails h WHERE b.bookingStatus = 'APPROVED' GROUP BY h.division") + List countBookingsByDivisions(); + + @Query("SELECT b FROM BookingDetails b JOIN b.hallDetails h WHERE h.zone = :zone AND b.bookingStatus = 'APPROVED'") List findByZone(@Param("zone") String zone); - - //gccapps - List findByBookingStatus(BookingDetails.BookingStatus bookingStatus); - - @Query("SELECT b FROM BookingDetails b JOIN FETCH b.settlement s WHERE b.refundStatus = 'WAITING'") - List findAllWithPendingRefundStatus(); - - @Query("SELECT b FROM BookingDetails b WHERE b.refundStatus = 'WAITING' AND b.bookingStatus = 'CANCELED'") - List findPendingCancelledList(); - - @Query(value = "SELECT * FROM booking_details WHERE refund_status = 'WAITING' AND booking_status IN ('GCC_BLOCKED', 'REJECTED')", nativeQuery = true) - List findPendingRejectedList(); - - @Query(value = "SELECT * FROM booking_details WHERE refund_status = 'COMPLETED' AND booking_status = 'CANCELED'", nativeQuery = true) - List findCompletedCancelledList(); - - @Query(value = "SELECT * FROM booking_details WHERE refund_status = 'COMPLETED' AND booking_status IN ('GCC_BLOCKED', 'REJECTED')", nativeQuery = true) - List findCompletedRejectedList(); - - @Query("SELECT b FROM BookingDetails b JOIN FETCH b.settlement s WHERE b.refundStatus = 'REJECTED'") - List findSettlementRejected(); - - @Query(value = "SELECT * FROM booking_details WHERE DATE(start_date) < CURRENT_DATE() AND booking_status='APPROVED'", nativeQuery = true) - List findPastsEvents(); - - @Query(value = "SELECT * FROM booking_details WHERE DATE(start_date) = CURRENT_DATE() AND booking_status='APPROVED'", nativeQuery = true) - List findPresentsEvents(); - - @Query(value = "SELECT * FROM booking_details WHERE DATE(start_date) BETWEEN CURRENT_DATE() AND DATE_ADD(CURRENT_DATE(), INTERVAL 2 DAY) AND booking_status = 'APPROVED'", nativeQuery = true) - List findFuturesEvents(); - - @Query(value = "SELECT * FROM booking_details WHERE DATE(start_date) < CURRENT_DATE() AND booking_status='APPROVED'", nativeQuery = true) - public List getSettlementApprovedList(); - - @Query(value = "SELECT * FROM booking_details WHERE DATE(start_date) <= CURRENT_DATE() AND booking_status='APPROVED'", nativeQuery = true) - public List getSettlementsList(); - - @Query("SELECT b FROM BookingDetails b WHERE b.refundStatus = 'FAILURE' AND b.bookingStatus = 'APPROVED' AND b.hallDetails.zone = :zone") - List findSettlementRefundFailedByZone(String zone); - @Query("SELECT b FROM BookingDetails b WHERE b.refundStatus = 'FAILURE' AND b.bookingStatus = 'CANCELED' AND b.hallDetails.zone = :zone") - List findRefundFaileCancelledListByZone(String zone); - @Query("SELECT b FROM BookingDetails b WHERE b.refundStatus = 'FAILURE' AND b.bookingStatus IN ('REJECTED','GCC_BLOCKED') AND b.hallDetails.zone = :zone") - List findRefundFaileRejectedListByZone(String zone); - @Query("SELECT b FROM BookingDetails b WHERE b.bookingStatus = 'COMPLETED' AND b.refundStatus IN ('COMPLETED','CLOSED') AND b.hallDetails.zone = :zone") - List findSettlementCompletedListbyzone(String zone); - @Query("SELECT b FROM BookingDetails b WHERE b.bookingStatus = 'CANCELED' AND b.refundStatus = 'COMPLETED' AND b.hallDetails.zone = :zone") - List findCancelledCompletedListbyzone(String zone); - @Query("SELECT b FROM BookingDetails b WHERE b.bookingStatus IN ('REJECTED','GCC_BLOCKED') AND b.refundStatus = 'COMPLETED' AND b.hallDetails.zone = :zone") - List findRejectedSettlementCompletedListbyzone(String zone); - @Query("SELECT b FROM BookingDetails b JOIN FETCH b.settlement s WHERE b.refundStatus = 'WAITING'") - List findAllSettlementPending(); - @Query("SELECT b FROM BookingDetails b WHERE b.refundStatus = 'WAITING' AND b.bookingStatus = 'CANCELED'") - List findAllSettlementCancelledList(); - @Query("SELECT b FROM BookingDetails b WHERE b.refundStatus = 'WAITING' AND b.bookingStatus IN ('REJECTED','GCC_BLOCKED')") - List findAllSettlementRejectedList(); - @Query("SELECT b FROM BookingDetails b WHERE b.refundStatus = 'FAILURE' AND b.bookingStatus = 'APPROVED'") - List findAllSettlementRefundFailed(); - @Query("SELECT b FROM BookingDetails b WHERE b.refundStatus = 'FAILURE' AND b.bookingStatus = 'CANCELED'") - List findAllRefundFaileCancelledList(); - @Query("SELECT b FROM BookingDetails b WHERE b.refundStatus = 'FAILURE' AND b.bookingStatus IN ('REJECTED','GCC_BLOCKED')") - List findAllRefundFaileRejectedList(); - - @Query("SELECT b FROM BookingDetails b JOIN FETCH b.settlement s WHERE b.refundStatus = 'REJECTED'") - List findAllSettlementRejected(); - - @Query(value = "SELECT * FROM booking_details WHERE DATE(start_date) <= CURRENT_DATE() AND booking_status='APPROVED' AND refund_status IN ('WAITING','REJECTED','APPROVED')", nativeQuery = true) - public List getAllSettlementList();} + + //gccapps + List findByBookingStatus(BookingDetails.BookingStatus bookingStatus); + + @Query("SELECT b FROM BookingDetails b JOIN FETCH b.settlement s WHERE b.refundStatus = 'WAITING'") + List findAllWithPendingRefundStatus(); + + @Query("SELECT b FROM BookingDetails b WHERE b.refundStatus = 'WAITING' AND b.bookingStatus = 'CANCELED'") + List findPendingCancelledList(); + + @Query(value = "SELECT * FROM booking_details WHERE refund_status = 'WAITING' AND booking_status IN ('GCC_BLOCKED', 'REJECTED')", nativeQuery = true) + List findPendingRejectedList(); + + @Query(value = "SELECT * FROM booking_details WHERE refund_status = 'COMPLETED' AND booking_status = 'CANCELED'", nativeQuery = true) + List findCompletedCancelledList(); + + @Query(value = "SELECT * FROM booking_details WHERE refund_status = 'COMPLETED' AND booking_status IN ('GCC_BLOCKED', 'REJECTED')", nativeQuery = true) + List findCompletedRejectedList(); + + @Query("SELECT b FROM BookingDetails b JOIN FETCH b.settlement s WHERE b.refundStatus = 'REJECTED'") + List findSettlementRejected(); + + @Query(value = "SELECT * FROM booking_details WHERE DATE(start_date) < CURRENT_DATE() AND booking_status='APPROVED'", nativeQuery = true) + List findPastsEvents(); + + @Query(value = "SELECT * FROM booking_details WHERE DATE(start_date) = CURRENT_DATE() AND booking_status='APPROVED'", nativeQuery = true) + List findPresentsEvents(); + + @Query(value = "SELECT * FROM booking_details WHERE DATE(start_date) BETWEEN CURRENT_DATE() AND DATE_ADD(CURRENT_DATE(), INTERVAL 2 DAY) AND booking_status = 'APPROVED'", nativeQuery = true) + List findFuturesEvents(); + + @Query(value = "SELECT * FROM booking_details WHERE DATE(start_date) < CURRENT_DATE() AND booking_status='APPROVED'", nativeQuery = true) + public List getSettlementApprovedList(); + + @Query(value = "SELECT * FROM booking_details WHERE DATE(start_date) <= CURRENT_DATE() AND booking_status='APPROVED'", nativeQuery = true) + public List getSettlementsList(); + + @Query("SELECT b FROM BookingDetails b WHERE b.refundStatus = 'FAILURE' AND b.bookingStatus = 'APPROVED' AND b.hallDetails.zone = :zone") + List findSettlementRefundFailedByZone(String zone); + + @Query("SELECT b FROM BookingDetails b WHERE b.refundStatus = 'FAILURE' AND b.bookingStatus = 'CANCELED' AND b.hallDetails.zone = :zone") + List findRefundFaileCancelledListByZone(String zone); + + @Query("SELECT b FROM BookingDetails b WHERE b.refundStatus = 'FAILURE' AND b.bookingStatus IN ('REJECTED','GCC_BLOCKED') AND b.hallDetails.zone = :zone") + List findRefundFaileRejectedListByZone(String zone); + + @Query("SELECT b FROM BookingDetails b WHERE b.bookingStatus = 'COMPLETED' AND b.refundStatus IN ('COMPLETED','CLOSED') AND b.hallDetails.zone = :zone") + List findSettlementCompletedListbyzone(String zone); + + @Query("SELECT b FROM BookingDetails b WHERE b.bookingStatus = 'CANCELED' AND b.refundStatus = 'COMPLETED' AND b.hallDetails.zone = :zone") + List findCancelledCompletedListbyzone(String zone); + + @Query("SELECT b FROM BookingDetails b WHERE b.bookingStatus IN ('REJECTED','GCC_BLOCKED') AND b.refundStatus = 'COMPLETED' AND b.hallDetails.zone = :zone") + List findRejectedSettlementCompletedListbyzone(String zone); + + @Query("SELECT b FROM BookingDetails b JOIN FETCH b.settlement s WHERE b.refundStatus = 'WAITING'") + List findAllSettlementPending(); + + @Query("SELECT b FROM BookingDetails b WHERE b.refundStatus = 'WAITING' AND b.bookingStatus = 'CANCELED'") + List findAllSettlementCancelledList(); + + @Query("SELECT b FROM BookingDetails b WHERE b.refundStatus = 'WAITING' AND b.bookingStatus IN ('REJECTED','GCC_BLOCKED')") + List findAllSettlementRejectedList(); + + @Query("SELECT b FROM BookingDetails b WHERE b.refundStatus = 'FAILURE' AND b.bookingStatus = 'APPROVED'") + List findAllSettlementRefundFailed(); + + @Query("SELECT b FROM BookingDetails b WHERE b.refundStatus = 'FAILURE' AND b.bookingStatus = 'CANCELED'") + List findAllRefundFaileCancelledList(); + + @Query("SELECT b FROM BookingDetails b WHERE b.refundStatus = 'FAILURE' AND b.bookingStatus IN ('REJECTED','GCC_BLOCKED')") + List findAllRefundFaileRejectedList(); + + + @Query(value = "SELECT * FROM booking_details WHERE booking_date = :bookingDate AND hall_details_hall_id = :hallId", nativeQuery = true) + List findByBookingDateAndHallId(@Param("bookingDate") LocalDate bookingDate, + @Param("hallId") Long hallId); + + @Query(value = "SELECT * FROM booking_details where booking_status='WAITING_FOR_NOC' order by booking_id", nativeQuery = true) + List getAllwaitingNOC(); + +} diff --git a/src/main/java/com/gcc/communityHall/repository/HallDetailsRepository.java b/src/main/java/com/gcc/communityHall/repository/HallDetailsRepository.java index fed5f4b3..99874dff 100644 --- a/src/main/java/com/gcc/communityHall/repository/HallDetailsRepository.java +++ b/src/main/java/com/gcc/communityHall/repository/HallDetailsRepository.java @@ -42,7 +42,8 @@ public interface HallDetailsRepository extends JpaRepository findActiveHalls(); - + + //admin dashboard @Query(nativeQuery = true, value ="SELECT SUM(CASE WHEN b.booking_status = 'APPROVED' THEN 1 ELSE 0 END) AS approvedCount,\r\n" diff --git a/src/main/java/com/gcc/communityHall/service/BookingService.java b/src/main/java/com/gcc/communityHall/service/BookingService.java index 89333c68..9aba87d7 100644 --- a/src/main/java/com/gcc/communityHall/service/BookingService.java +++ b/src/main/java/com/gcc/communityHall/service/BookingService.java @@ -16,7 +16,6 @@ import com.gcc.communityHall.entity.BookingDetails.BookingStatus; import com.gcc.communityHall.entity.BookingDetails.RefundStatus; import com.gcc.communityHall.entity.EbDetails; import com.gcc.communityHall.entity.GccBlockingDate; -import com.gcc.communityHall.paymentService.entity.TransactionResponse; public interface BookingService { BookingDetails getBookingsById(int BookingId); @@ -150,5 +149,7 @@ List getAllExtraPaymentsDetails( String fromDate, String toDate,String //developer List getTransactionresponse(String fromDate, String toDate, Long bookingId,Long hallId); List getRefundResponse(String fromDate, String toDate, Long bookingId); -List getBookingCalendarDetails(String fromDate, String toDate,Long bookingId ,String hallName); +List getBookingCalendarDetails(String fromDate, String toDate, Long bookingId,String hallName); + + List getBookingsByDateAndHall(String bookingDate, Long hallId); } diff --git a/src/main/java/com/gcc/communityHall/service/Impl/BookingServiceImpl.java b/src/main/java/com/gcc/communityHall/service/Impl/BookingServiceImpl.java index 9595844a..a684336f 100644 --- a/src/main/java/com/gcc/communityHall/service/Impl/BookingServiceImpl.java +++ b/src/main/java/com/gcc/communityHall/service/Impl/BookingServiceImpl.java @@ -3,49 +3,70 @@ package com.gcc.communityHall.service.Impl; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; -import java.math.BigDecimal; -import java.net.InetAddress; -import java.net.UnknownHostException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; -import java.util.*; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.atomic.AtomicInteger; +import java.util.ArrayList; +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.net.SyslogOutputStream; -import com.gcc.communityHall.entity.*; -import com.gcc.communityHall.repository.*; import jakarta.servlet.http.HttpSession; -import lombok.Synchronized; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; -import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; -import org.springframework.transaction.support.DefaultTransactionDefinition; -import org.springframework.web.client.RestTemplate; import org.springframework.web.multipart.MultipartFile; +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.exception.PaymentRefundSlotOccupiedException; +import com.gcc.communityHall.entity.BookingDocuments; +import com.gcc.communityHall.entity.BookingHistory; +import com.gcc.communityHall.entity.Damage; +import com.gcc.communityHall.entity.DiscountRange; +import com.gcc.communityHall.entity.EbDetails; +import com.gcc.communityHall.entity.GccBlockingDate; +import com.gcc.communityHall.entity.GccBlockingHistory; +import com.gcc.communityHall.entity.GccblockingDocuments; +import com.gcc.communityHall.entity.HallDetails; +import com.gcc.communityHall.entity.HallDetailsConcession; +import com.gcc.communityHall.entity.ReasonDocumentMaster; +import com.gcc.communityHall.entity.ReasonMaster; +import com.gcc.communityHall.entity.Settlement; +import com.gcc.communityHall.entity.Users; import com.gcc.communityHall.exception.SlotOccupiedException; import com.gcc.communityHall.others.UserSession; import com.gcc.communityHall.paymentService.repository.TransRefundResRepository; import com.gcc.communityHall.paymentService.repository.TransactionResponseRepository; import com.gcc.communityHall.paymentService.service.PaymentGatewayService; +import com.gcc.communityHall.repository.ApplicationLogsRepository; +import com.gcc.communityHall.repository.BookingCalendarRepository; +import com.gcc.communityHall.repository.BookingDetailsRepository; +import com.gcc.communityHall.repository.BookingDocumentsRepository; +import com.gcc.communityHall.repository.BookingHistoryRepository; +import com.gcc.communityHall.repository.DamageRepository; +import com.gcc.communityHall.repository.EbDetailsRepository; +import com.gcc.communityHall.repository.GccBlockingDateRepository; +import com.gcc.communityHall.repository.GccBlockingHistoryRepository; +import com.gcc.communityHall.repository.GccblockingDocumentsRepo; +import com.gcc.communityHall.repository.HallDetailsConcessionRepo; +import com.gcc.communityHall.repository.HallDetailsRepository; +import com.gcc.communityHall.repository.ReasonMasterRepository; +import com.gcc.communityHall.repository.SettlementRepository; +import com.gcc.communityHall.repository.UsersRepository; import com.gcc.communityHall.service.ApplicationLogService; import com.gcc.communityHall.service.BookingService; import com.gcc.communityHall.service.DiscountRangeService; @@ -54,7 +75,7 @@ import com.gcc.communityHall.service.ReasonMasterService; import com.gcc.communityHall.service.UserService; @Service -public class BookingServiceImpl implements BookingService { +public class BookingServiceImpl implements BookingService { @Autowired private BookingDetailsRepository bookingDetailsRepository; @@ -68,7 +89,7 @@ public class BookingServiceImpl implements BookingService { @Autowired private UserService userService; - + @Autowired private UsersRepository userRepository; @@ -98,50 +119,42 @@ public class BookingServiceImpl implements BookingService { @Autowired private PaymentGatewayService paymentGatewayService; - + @Autowired private GccBlockingDateRepository blockingDateRepository; - + @Autowired private DiscountRangeService discountRangeService; - + @Autowired private HallDetailsRepository hallDetailsRepository; - + @Autowired private GccBlockingHistoryRepository blockingHistoryRepository; - + @Autowired private WhatsappMsgServiceImpl whatsappMsgServiceImpl; - + @Autowired private GccblockingDocumentsRepo gccblockingDocumentsRepo; - + @Autowired private HttpSession session; - + @Autowired private HallDetailsConcessionRepo hallDetailsConcessionRepo; - + @Autowired private ReasonMasterRepository reasonMasterRepository; - + @Autowired private ApplicationLogsRepository applicationLogsRepository; - + @Autowired private TransactionResponseRepository transactionResponseRepository; - - @Autowired - private TransRefundResRepository transRefundResRepository; @Autowired - private QueueLogRepository queueLogRepository; - - private static final Map> bookingQueueMap = new ConcurrentHashMap<>(); - private static final Map lockedSlots = new ConcurrentHashMap<>(); - private static final Map slotTimers = new ConcurrentHashMap<>(); - + private TransRefundResRepository transRefundResRepository; @Value("${file.upload.directory}") private String uploadDirectory; @@ -150,14 +163,14 @@ public class BookingServiceImpl implements BookingService { private String serverPath; private final PlatformTransactionManager transactionManager; - public BookingServiceImpl( PlatformTransactionManager transactionManager) { + public BookingServiceImpl(PlatformTransactionManager transactionManager) { this.transactionManager = transactionManager; } @Override public BookingDetails getBookingsById(int BookingId) { - Optional OPBookingDetails =bookingDetailsRepository.findById(BookingId); - if(OPBookingDetails.isPresent()) { + Optional OPBookingDetails = bookingDetailsRepository.findById(BookingId); + if (OPBookingDetails.isPresent()) { return OPBookingDetails.get(); } return null; @@ -169,84 +182,85 @@ public class BookingServiceImpl implements BookingService { } @Override - public BookingDetails updateBookingStatus(int bookingId, BookingStatus status, String comments) { - Optional booking= bookingDetailsRepository.findById(bookingId); - if(booking.isPresent()){ - BookingDetails book = booking.get(); - BookingHistory bookingHistory = new BookingHistory(); - bookingHistory.setBookingDetails(book); - bookingHistory.setStartDate(book.getStartDate()); - bookingHistory.setEndDate(book.getEndDate()); - bookingHistory.setBookingStatus(book.getBookingStatus()); - bookingHistory.setComments(book.getComments()); - bookingHistory.setCdate(new Date()); - bookingHistory.setRefundStatus(book.getRefundStatus()); - bookingHistoryRepository.save(bookingHistory); - - book.setBookingStatus(status); - book.setComments(comments); - BookingDetails bookings = bookingDetailsRepository.save(book); - return bookings; - } - return null; + public BookingDetails updateBookingStatus(int bookingId, BookingDetails.BookingStatus status, String comments) { + Optional booking = bookingDetailsRepository.findById(bookingId); + if (booking.isPresent()) { + BookingDetails book = booking.get(); + BookingHistory bookingHistory = new BookingHistory(); + bookingHistory.setBookingDetails(book); + bookingHistory.setStartDate(book.getStartDate()); + bookingHistory.setEndDate(book.getEndDate()); + bookingHistory.setBookingStatus(book.getBookingStatus()); + bookingHistory.setComments(book.getComments()); + bookingHistory.setCdate(new Date()); + bookingHistory.setRefundStatus(book.getRefundStatus()); + bookingHistoryRepository.save(bookingHistory); + + book.setBookingStatus(status); + book.setComments(comments); + BookingDetails bookings = bookingDetailsRepository.save(book); + return bookings; + } + return null; } + @Override public String confirmTheDateAndSlot(String fromDate, String toDate, int days, int fromStartingSlot, int fromEndingSlot, int toStartingSlot, int toEndingSlot, int bookingId, int userId) { return null; } + @Override @Transactional - public String confirmBooking(int bookingId) { - String exMsg= "Slot occupied"; + public String confirmBooking(int bookingId) { + String exMsg = "Slot occupied"; BookingDetails bookingDetails = null; try { Optional bookingDet = bookingDetailsRepository.findById(bookingId); - if (!bookingDet.isPresent()){ + if (!bookingDet.isPresent()) { // Handle invalid booking ID return "Invalid booking ID"; } - bookingDetails=bookingDet.get(); + bookingDetails = bookingDet.get(); // Validate booking details - int hallId =bookingDetails.getHallDetails().getHallId(); + int hallId = bookingDetails.getHallDetails().getHallId(); LocalDate startDate = LocalDate.parse(bookingDetails.getStartDate()); LocalDate endDate = LocalDate.parse(bookingDetails.getEndDate()); // Iterate through each date of the booking - int i=0; + int i = 0; for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) { BookingCalendar bookingCalendar = bookingCalendarRepository.findByBdateAndHallId(date, hallId); if (bookingCalendar != null) { - - if(bookingCalendar.getIs_blocked()){ - throw new RuntimeException("GCC Blocked Date"); - } - // System.out.println(bookingCalendar.toString()); - // System.out.println("date:-"+date ); - // System.out.println("bookingDetails.getEndingSlot() :- "+bookingDetails.getEndingSlot()); + // System.out.println(bookingCalendar.toString()); + // System.out.println("date:-"+date ); + // System.out.println("bookingDetails.getEndingSlot() :- "+bookingDetails.getEndingSlot()); //System.out.println("bookingCalendar.isMorningSlot():-"+bookingCalendar.isMorningSlot()); //System.out.println(date.equals(endDate) && bookingDetails.getEndingSlot() == 1 && bookingCalendar.isMorningSlot()); //System.out.println(); // Check if the slot is already occupied - else if ((date.equals(startDate) && bookingDetails.getStartingSlot() == 1 && bookingCalendar.isMorningSlot()) || + if (bookingCalendar.getIs_blocked()) { + throw new RuntimeException("GCC Blocked Date"); + } else if ((date.equals(startDate) && bookingDetails.getStartingSlot() == 1 && bookingCalendar.isMorningSlot()) || (date.equals(startDate) && bookingDetails.getStartingSlot() == 2 && bookingCalendar.isEveningSlot()) || (date.equals(endDate) && bookingDetails.getEndingSlot() == 1 && bookingCalendar.isMorningSlot()) || (date.equals(endDate) && bookingDetails.getEndingSlot() == 2 && bookingCalendar.isEveningSlot())) { + //System.out.println("booking slot occupied:- 218"); - throw new RuntimeException(exMsg); - }else if(bookingCalendar.isMorningSlot() && bookingCalendar.isEveningSlot() ) { + throw new RuntimeException(exMsg); + } else if (bookingCalendar.isMorningSlot() && bookingCalendar.isEveningSlot()) { //System.out.println("booking slot occupied:- 221"); - throw new RuntimeException(exMsg); + throw new RuntimeException(exMsg); - } else if (!date.equals(endDate) && i!=0 && i != Math.round(bookingDetails.getNoOfDays() -1) + } else if (!date.equals(endDate) && i != 0 && i != Math.round(bookingDetails.getNoOfDays() - 1) && (bookingCalendar.isMorningSlot() || bookingCalendar.isEveningSlot())) { //System.out.println("booking slot occupied:- 227 :-"+Math.round(bookingDetails.getNoOfDays()-1) ); - throw new RuntimeException(exMsg);} - else if(date.equals(endDate) && bookingDetails.getEndingSlot() == 2 && bookingCalendar.isMorningSlot() - && i!=0 && i == Math.round(bookingDetails.getNoOfDays() -1)){ - // System.out.println("booking slot occupied:- 240 :-"+Math.round(bookingDetails.getNoOfDays()-1) ); - throw new RuntimeException(exMsg); + throw new RuntimeException(exMsg); + } else if (date.equals(endDate) && bookingDetails.getEndingSlot() == 2 && bookingCalendar.isMorningSlot() + && i != 0 && i == Math.round(bookingDetails.getNoOfDays() - 1)) { + // System.out.println("booking slot occupied:- 240 :-"+Math.round(bookingDetails.getNoOfDays()-1) ); + throw new RuntimeException(exMsg); } } else { @@ -264,113 +278,109 @@ public class BookingServiceImpl implements BookingService { if (bookingDetails.getStartingSlot() == 1) { bookingCalendar.setMorningSlot(true); bookingCalendar.setBookingId_1(String.valueOf(bookingId)); - bookingCalendar.setIs_booked(bookingCalendar.getIs_booked()+1); - if(!date.equals(endDate)){ + bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1); + if (!date.equals(endDate)) { bookingCalendar.setEveningSlot(true); bookingCalendar.setBookingId_2(String.valueOf(bookingId)); - bookingCalendar.setIs_booked(bookingCalendar.getIs_booked()+1); - } - else if (startDate.equals(endDate) && bookingDetails.getStartingSlot() == 1 && bookingDetails.getEndingSlot()==2) { + bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1); + } else if (startDate.equals(endDate) && bookingDetails.getStartingSlot() == 1 && bookingDetails.getEndingSlot() == 2) { bookingCalendar.setEveningSlot(true); bookingCalendar.setBookingId_2(String.valueOf(bookingId)); - bookingCalendar.setIs_booked(bookingCalendar.getIs_booked()+1); + bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1); } - bookingCalendar.setTemp_blocked(false); } else { bookingCalendar.setEveningSlot(true); bookingCalendar.setBookingId_2(String.valueOf(bookingId)); - bookingCalendar.setIs_booked(bookingCalendar.getIs_booked()+1); - bookingCalendar.setTemp_blocked(false); + bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1); } } else if (date.equals(endDate)) { if (bookingDetails.getEndingSlot() == 1) { bookingCalendar.setMorningSlot(true); bookingCalendar.setBookingId_1(String.valueOf(bookingId)); - bookingCalendar.setIs_booked(bookingCalendar.getIs_booked()+1); + bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1); } else { bookingCalendar.setEveningSlot(true); bookingCalendar.setBookingId_2(String.valueOf(bookingId)); - bookingCalendar.setIs_booked(bookingCalendar.getIs_booked()+1); - if(bookingDetails.getEndingSlot()==2){ + bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1); + if (bookingDetails.getEndingSlot() == 2) { bookingCalendar.setMorningSlot(true); bookingCalendar.setBookingId_1(String.valueOf(bookingId)); - bookingCalendar.setIs_booked(bookingCalendar.getIs_booked()+1); + bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1); } } - bookingCalendar.setTemp_blocked(false); } else { // For dates between start and end date, mark both slots as booked bookingCalendar.setMorningSlot(true); bookingCalendar.setEveningSlot(true); bookingCalendar.setBookingId_1(String.valueOf(bookingId)); bookingCalendar.setBookingId_2(String.valueOf(bookingId)); - bookingCalendar.setIs_booked(bookingCalendar.getIs_booked()+2); - bookingCalendar.setTemp_blocked(false); + bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 2); } - // System.out.println(i + "end:-"+bookingCalendar.toString()); + + // System.out.println(i + "end:-"+bookingCalendar.toString()); bookingCalendarRepository.save(bookingCalendar); i++; } - String reason=bookingDetails.getReason(); - ReasonMaster reasondetails=reasonMasterRepository.findByReason(reason); - String reasoncode=reasondetails.getReasoncode(); + String reason = bookingDetails.getReason(); + ReasonMaster reasondetails = reasonMasterRepository.findByReason(reason); + String reasoncode = reasondetails.getReasoncode(); if (reasoncode == null) { reasoncode = ""; // or any default value } - if(reasoncode.equals("CGE") || reasoncode.equals("CAO") || reasoncode.equals("SGE")) { - updateBookingStatusById(bookingDetails.getBookingId(), BookingStatus.WAITING_FOR_NOC, "Waiting For NOC Documents"); - String bookingconfirmationmsg="Your booking ID "+bookingDetails.getBookingId()+" on "+bookingDetails.getBookingDate()+" has been confirmed successfully. Thanks for using GCC Community Hall Booking System."; - String urlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to="+bookingDetails.getUsers().getMobileNo()+"&from=GCCCRP&body="+bookingconfirmationmsg+"&entityid=1401572690000011081&templateid=1407172346459428987"; - String whatsupmsg="https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to="+bookingDetails.getUsers().getMobileNo()+"&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+booking+with+ID+"+bookingDetails.getBookingId()+"+on+"+bookingDetails.getBookingDate()+"+has+been+successfully+confirmed.+%0AThanks+for+using+GCC+Community+Hall+Booking+System."; + if (reasoncode.equals("CGE") || reasoncode.equals("CAO") || reasoncode.equals("SGE")) { + updateBookingStatusById(bookingDetails.getBookingId(), BookingDetails.BookingStatus.WAITING_FOR_NOC, "Waiting For NOC Documents"); + String bookingconfirmationmsg = "Your booking ID " + bookingDetails.getBookingId() + " on " + bookingDetails.getBookingDate() + " has been confirmed successfully. Thanks for using GCC Community Hall Booking System."; + String urlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + bookingDetails.getUsers().getMobileNo() + "&from=GCCCRP&body=" + bookingconfirmationmsg + "&entityid=1401572690000011081&templateid=1407172346459428987"; + String whatsupmsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + bookingDetails.getUsers().getMobileNo() + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+booking+with+ID+" + bookingDetails.getBookingId() + "+on+" + bookingDetails.getBookingDate() + "+has+been+successfully+confirmed.+%0AThanks+for+using+GCC+Community+Hall+Booking+System."; whatsappMsgServiceImpl.sendMsg(whatsupmsg); whatsappMsgServiceImpl.sendSMS(urlString); return "Waiting For NOC Documents"; - }else { - updateBookingStatusById(bookingDetails.getBookingId(), BookingStatus.APPROVED, "Booking Confirmed Successfully"); - String bookingconfirmationmsg="Your booking ID "+bookingDetails.getBookingId()+" on "+bookingDetails.getBookingDate()+" has been confirmed successfully. Thanks for using GCC Community Hall Booking System."; - String urlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to="+bookingDetails.getUsers().getMobileNo()+"&from=GCCCRP&body="+bookingconfirmationmsg+"&entityid=1401572690000011081&templateid=1407172346459428987"; - String whatsupmsg="https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to="+bookingDetails.getUsers().getMobileNo()+"&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+booking+with+ID+"+bookingDetails.getBookingId()+"+on+"+bookingDetails.getBookingDate()+"+has+been+successfully+confirmed.+%0AThanks+for+using+GCC+Community+Hall+Booking+System."; + } else { + updateBookingStatusById(bookingDetails.getBookingId(), BookingDetails.BookingStatus.APPROVED, "Booking Confirmed Successfully"); + String bookingconfirmationmsg = "Your booking ID " + bookingDetails.getBookingId() + " on " + bookingDetails.getStartDate() + " has been confirmed successfully. Thanks for using GCC Community Hall Booking System."; + String urlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + bookingDetails.getUsers().getMobileNo() + "&from=GCCCRP&body=" + bookingconfirmationmsg + "&entityid=1401572690000011081&templateid=1407172346459428987"; + String whatsupmsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + bookingDetails.getUsers().getMobileNo() + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+booking+with+ID+" + bookingDetails.getBookingId() + "+on+" + bookingDetails.getStartDate() + "+has+been+successfully+confirmed.+%0AThanks+for+using+GCC+Community+Hall+Booking+System."; whatsappMsgServiceImpl.sendMsg(whatsupmsg); whatsappMsgServiceImpl.sendSMS(urlString); return "Booking confirmed successfully"; } - }catch (Exception e ) { + } catch (Exception e) { bookingFailure(bookingDetails); - // System.out.println(bookingDetails.getBookingStatus()+","+bookingDetails.getRefundStatus()+","+bookingDetails.getComments()); + // System.out.println(bookingDetails.getBookingStatus()+","+bookingDetails.getRefundStatus()+","+bookingDetails.getComments()); return "redirect:/communityhall/user/acknowledgement?bookingId=" + bookingDetails.getBookingId(); } } - + @Override @Transactional - public String confirmStateBooking(int bookingId) { - String exMsg= "Slot occupied"; + public String confirmStateBooking(int bookingId) { + String exMsg = "Slot occupied"; BookingDetails bookingDetails = null; try { Optional bookingDet = bookingDetailsRepository.findById(bookingId); - if (!bookingDet.isPresent()){ + if (!bookingDet.isPresent()) { // Handle invalid booking ID return "Invalid booking ID"; } - bookingDetails=bookingDet.get(); + bookingDetails = bookingDet.get(); // Validate booking details - int hallId =bookingDetails.getHallDetails().getHallId(); + int hallId = bookingDetails.getHallDetails().getHallId(); LocalDate startDate = LocalDate.parse(bookingDetails.getStartDate()); LocalDate endDate = LocalDate.parse(bookingDetails.getEndDate()); // Iterate through each date of the booking - int i=0; + int i = 0; for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) { BookingCalendar bookingCalendar = bookingCalendarRepository.findByBdateAndHallId(date, hallId); if (bookingCalendar != null) { - // System.out.println(bookingCalendar.toString()); - // System.out.println("date:-"+date ); - // System.out.println("bookingDetails.getEndingSlot() :- "+bookingDetails.getEndingSlot()); + // System.out.println(bookingCalendar.toString()); + // System.out.println("date:-"+date ); + // System.out.println("bookingDetails.getEndingSlot() :- "+bookingDetails.getEndingSlot()); //System.out.println("bookingCalendar.isMorningSlot():-"+bookingCalendar.isMorningSlot()); //System.out.println(date.equals(endDate) && bookingDetails.getEndingSlot() == 1 && bookingCalendar.isMorningSlot()); //System.out.println(); @@ -380,19 +390,19 @@ public class BookingServiceImpl implements BookingService { (date.equals(endDate) && bookingDetails.getEndingSlot() == 1 && bookingCalendar.isMorningSlot()) || (date.equals(endDate) && bookingDetails.getEndingSlot() == 2 && bookingCalendar.isEveningSlot())) { //System.out.println("booking slot occupied:- 218"); - throw new RuntimeException(exMsg); - }else if(bookingCalendar.isMorningSlot() && bookingCalendar.isEveningSlot() ) { + throw new RuntimeException(exMsg); + } else if (bookingCalendar.isMorningSlot() && bookingCalendar.isEveningSlot()) { //System.out.println("booking slot occupied:- 221"); - throw new RuntimeException(exMsg); + throw new RuntimeException(exMsg); - } else if (!date.equals(endDate) && i!=0 && i != Math.round(bookingDetails.getNoOfDays() -1) + } else if (!date.equals(endDate) && i != 0 && i != Math.round(bookingDetails.getNoOfDays() - 1) && (bookingCalendar.isMorningSlot() || bookingCalendar.isEveningSlot())) { //System.out.println("booking slot occupied:- 227 :-"+Math.round(bookingDetails.getNoOfDays()-1) ); - throw new RuntimeException(exMsg);} - else if(date.equals(endDate) && bookingDetails.getEndingSlot() == 2 && bookingCalendar.isMorningSlot() - && i!=0 && i == Math.round(bookingDetails.getNoOfDays() -1)){ - // System.out.println("booking slot occupied:- 240 :-"+Math.round(bookingDetails.getNoOfDays()-1) ); - throw new RuntimeException(exMsg); + throw new RuntimeException(exMsg); + } else if (date.equals(endDate) && bookingDetails.getEndingSlot() == 2 && bookingCalendar.isMorningSlot() + && i != 0 && i == Math.round(bookingDetails.getNoOfDays() - 1)) { + // System.out.println("booking slot occupied:- 240 :-"+Math.round(bookingDetails.getNoOfDays()-1) ); + throw new RuntimeException(exMsg); } } else { @@ -410,36 +420,35 @@ public class BookingServiceImpl implements BookingService { if (bookingDetails.getStartingSlot() == 1) { bookingCalendar.setMorningSlot(true); bookingCalendar.setBookingId_1(String.valueOf(bookingId)); - bookingCalendar.setIs_booked(bookingCalendar.getIs_booked()+1); - if(!date.equals(endDate)){ + bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1); + if (!date.equals(endDate)) { bookingCalendar.setEveningSlot(true); bookingCalendar.setBookingId_2(String.valueOf(bookingId)); - bookingCalendar.setIs_booked(bookingCalendar.getIs_booked()+1); - } - else if (startDate.equals(endDate) && bookingDetails.getStartingSlot() == 1 && bookingDetails.getEndingSlot()==2) { + bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1); + } else if (startDate.equals(endDate) && bookingDetails.getStartingSlot() == 1 && bookingDetails.getEndingSlot() == 2) { bookingCalendar.setEveningSlot(true); bookingCalendar.setBookingId_2(String.valueOf(bookingId)); - bookingCalendar.setIs_booked(bookingCalendar.getIs_booked()+1); + bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1); } } else { bookingCalendar.setEveningSlot(true); bookingCalendar.setBookingId_2(String.valueOf(bookingId)); - bookingCalendar.setIs_booked(bookingCalendar.getIs_booked()+1); + bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1); } } else if (date.equals(endDate)) { if (bookingDetails.getEndingSlot() == 1) { bookingCalendar.setMorningSlot(true); bookingCalendar.setBookingId_1(String.valueOf(bookingId)); - bookingCalendar.setIs_booked(bookingCalendar.getIs_booked()+1); + bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1); } else { bookingCalendar.setEveningSlot(true); bookingCalendar.setBookingId_2(String.valueOf(bookingId)); - bookingCalendar.setIs_booked(bookingCalendar.getIs_booked()+1); - if(bookingDetails.getEndingSlot()==2){ + bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1); + if (bookingDetails.getEndingSlot() == 2) { bookingCalendar.setMorningSlot(true); bookingCalendar.setBookingId_1(String.valueOf(bookingId)); - bookingCalendar.setIs_booked(bookingCalendar.getIs_booked()+1); + bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1); } } } else { @@ -448,81 +457,71 @@ public class BookingServiceImpl implements BookingService { bookingCalendar.setEveningSlot(true); bookingCalendar.setBookingId_1(String.valueOf(bookingId)); bookingCalendar.setBookingId_2(String.valueOf(bookingId)); - bookingCalendar.setIs_booked(bookingCalendar.getIs_booked()+2); + bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 2); } - // System.out.println(i + "end:-"+bookingCalendar.toString()); + // System.out.println(i + "end:-"+bookingCalendar.toString()); bookingCalendarRepository.save(bookingCalendar); i++; } - updateBookingStatusById(bookingDetails.getBookingId(), BookingStatus.WAITING_FOR_NOC, "Waiting for NOC Documents"); - String bookingconfirmationmsg="Your booking ID "+bookingDetails.getBookingId()+" on "+bookingDetails.getBookingDate()+" has been confirmed successfully. Thanks for using GCC Community Hall Booking System."; - String urlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to="+bookingDetails.getUsers().getMobileNo()+"&from=GCCCRP&body="+bookingconfirmationmsg+"&entityid=1401572690000011081&templateid=1407172346459428987"; - String whatsupmsg="https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to="+bookingDetails.getUsers().getMobileNo()+"&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+booking+with+ID+"+bookingDetails.getBookingId()+"+on+"+bookingDetails.getBookingDate()+"+has+been+successfully+confirmed.+%0AThanks+for+using+GCC+Community+Hall+Booking+System."; - whatsappMsgServiceImpl.sendMsg(whatsupmsg); - whatsappMsgServiceImpl.sendSMS(urlString); - return "redirect:/communityhall/user/acknowledgement?bookingId=" + bookingDetails.getBookingId(); - - }catch (Exception e ) { + updateBookingStatusById(bookingDetails.getBookingId(), BookingDetails.BookingStatus.WAITING_FOR_NOC, "Waiting for NOC Documents"); + String bookingconfirmationmsg = "Your booking ID " + bookingDetails.getBookingId() + " on " + bookingDetails.getBookingDate() + " has been confirmed successfully. Thanks for using GCC Community Hall Booking System."; + String urlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + bookingDetails.getUsers().getMobileNo() + "&from=GCCCRP&body=" + bookingconfirmationmsg + "&entityid=1401572690000011081&templateid=1407172346459428987"; + String whatsupmsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + bookingDetails.getUsers().getMobileNo() + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+booking+with+ID+" + bookingDetails.getBookingId() + "+on+" + bookingDetails.getBookingDate() + "+has+been+successfully+confirmed.+%0AThanks+for+using+GCC+Community+Hall+Booking+System."; + whatsappMsgServiceImpl.sendMsg(whatsupmsg); + whatsappMsgServiceImpl.sendSMS(urlString); + return "redirect:/communityhall/user/acknowledgement?bookingId=" + bookingDetails.getBookingId(); + + } catch (Exception e) { bookingFailure(bookingDetails); - // System.out.println(bookingDetails.getBookingStatus()+","+bookingDetails.getRefundStatus()+","+bookingDetails.getComments()); + // System.out.println(bookingDetails.getBookingStatus()+","+bookingDetails.getRefundStatus()+","+bookingDetails.getComments()); return "redirect:/communityhall/user/acknowledgement?bookingId=" + bookingDetails.getBookingId(); } } @Transactional(propagation = Propagation.REQUIRES_NEW) - public String bookingFailure(BookingDetails bookingDetails){ - // System.out.println("Booking Failure:-"+bookingDetails.getBookingId()); + public String bookingFailure(BookingDetails bookingDetails) { + // System.out.println("Booking Failure:-"+bookingDetails.getBookingId()); bookingDetails.setBookingStatus(BookingStatus.REFUNDED); bookingDetails.setComments("Slot occupied by other user,Amount paid will be refunded."); bookingDetailsRepository.save(bookingDetails); - if(!(bookingDetails.getRefundStatus()==RefundStatus.COMPLETED) && !(bookingDetails.getRefundStatus()==RefundStatus.CLOSED)) { - // BookingDetails bd =updateBookingStatusById(bookingDetails.getBookingId(), BookingDetails.BookingStatus.REFUNDED, "slot occupied Refund will happen shortly"); - applicationLogService.saveLog(bookingDetails.getBookingId(), ApplicationLogs.logsOfMsg.REFUNDED.toString(), "Refund will happen shortly"); - try { - String refundedMsg = paymentGatewayService.refundTheAmount(bookingDetails.getBookingId(), bookingDetails.getUsers().getUserId()); - //System.out.println("refundedMsg=="+refundedMsg); - if (refundedMsg.equals("Refunded")) { - //System.out.println("Refund completed........"); - bookingDetails.setRefundStatus(RefundStatus.COMPLETED); - bookingDetailsRepository.save(bookingDetails); - //System.out.println("refundStatus===="+bookingDetails.getRefundStatus()); - long mobile = bookingDetails.getUsers().getMobileNo(); - int bookingId= bookingDetails.getBookingId(); - double refundAmt = bookingDetails.getAmountReceived(); + if (!(bookingDetails.getRefundStatus() == RefundStatus.COMPLETED) && !(bookingDetails.getRefundStatus() == RefundStatus.CLOSED)) { + // BookingDetails bd =updateBookingStatusById(bookingDetails.getBookingId(), BookingDetails.BookingStatus.REFUNDED, "slot occupied Refund will happen shortly"); + applicationLogService.saveLog(bookingDetails.getBookingId(), ApplicationLogs.logsOfMsg.REFUNDED.toString(), "Refund will happen shortly"); + try { + String refundedMsg = paymentGatewayService.refundTheAmount(bookingDetails.getBookingId(), bookingDetails.getUsers().getUserId()); + //System.out.println("refundedMsg=="+refundedMsg); + if (refundedMsg.equals("Refunded")) { + //System.out.println("Refund completed........"); + bookingDetails.setRefundStatus(BookingDetails.RefundStatus.COMPLETED); + bookingDetailsRepository.save(bookingDetails); + //System.out.println("refundStatus===="+bookingDetails.getRefundStatus()); + long mobile = bookingDetails.getUsers().getMobileNo(); + int bookingId = bookingDetails.getBookingId(); + double refundAmt = bookingDetails.getAmountReceived(); // Thread thread = new Thread(() -> { - String settlementrefundsms="Your refund amount of Rs. "+refundAmt+" for Booking ID "+bookingId+" has been initiated. The amount will be credited to your account within 3 to 15 days. Thanks for using the GCC Community Hall Booking System."; - String settlementrefundurlString ="https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to="+mobile+"&from=GCCCRP&body="+settlementrefundsms+"&entityid=1401572690000011081&templateid=1407172346804951524"; - String settlementrefundwhatsupmsg="https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to="+mobile+"&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+refund+of+Rs.+"+refundAmt+"+for+Booking+ID+"+bookingId+"+has+been+initiated.+%0AThe+amount+will+be+credited+to+your+account+within+3+to+15+days."; - whatsappMsgServiceImpl.sendMsg(settlementrefundwhatsupmsg); - whatsappMsgServiceImpl.sendSMS(settlementrefundurlString); + String settlementrefundsms = "Your refund amount of Rs. " + refundAmt + " for Booking ID " + bookingId + " has been initiated. The amount will be credited to your account within 3 to 15 days. Thanks for using the GCC Community Hall Booking System."; + String settlementrefundurlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + mobile + "&from=GCCCRP&body=" + settlementrefundsms + "&entityid=1401572690000011081&templateid=1407172346804951524"; + String settlementrefundwhatsupmsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + mobile + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+refund+of+Rs.+" + refundAmt + "+for+Booking+ID+" + bookingId + "+has+been+initiated.+%0AThe+amount+will+be+credited+to+your+account+within+3+to+15+days."; + whatsappMsgServiceImpl.sendMsg(settlementrefundwhatsupmsg); + whatsappMsgServiceImpl.sendSMS(settlementrefundurlString); // }); // thread.start(); - return "Success"; + return "Success"; + } + } catch (Exception e) { + applicationLogService.saveLog(bookingDetails.getBookingId(), ApplicationLogs.logsOfMsg.ERROR.toString(), "Refund Error"); + return "error"; } } - - catch (Exception e){ - applicationLogService.saveLog(bookingDetails.getBookingId(), ApplicationLogs.logsOfMsg.ERROR.toString(), "Refund Error"); - return "error"; - }} return "error"; } @Override public Map saveBookingDetails(Map formData) { - Map hs = new HashMap<>(); BookingDetails bookingDetails = null; - BookingCalendar bookingCal = new BookingCalendar(); - QueueLog queueLog = new QueueLog(); - Optional existingBooking = Optional.empty(); - int bcid; - -// System.out.println("bc Id 2........"+formData.get("bcId")); - - AtomicInteger finalBcId = new AtomicInteger(); Integer userId = userSession.getUserId(); @@ -563,136 +562,11 @@ public class BookingServiceImpl implements BookingService { hs.put("actualhallamount", hallAmount); double discountAmount = 0; String usertype = user.getUsertype().toString(); - String reason=reasonMaster.getReason(); + String reason = reasonMaster.getReason(); + //double depositeamount = hallDetails.getDepositAmount() * daysrange; double depositeamount = hallDetails.getDepositAmount() * Math.ceil(days); - // Adjust slotKey to consider multiple dates - //String slotKey = hallDetails.getHallId() + "|" + startDate + "|" + endDate + "|" + startingSlot + "|" + endingSlot; - String slotKey = hallDetails.getHallId() + "|" + startDate + "|" + endDate ;//21212202413122024 - System.out.println("slotKey: " + slotKey); - - // Generate individual keys for each day within the range - List slotKeysForDates = new ArrayList<>(); - DateTimeFormatter dFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); - LocalDate formattedStartDate = LocalDate.parse(startDate, dFormatter); - LocalDate formattedEndDate = LocalDate.parse(endDate, dFormatter); - int hallId1 = bookingDetails.getHallDetails().getHallId(); - - for (LocalDate date = formattedStartDate; !date.isAfter(formattedEndDate); date = date.plusDays(1)) { - slotKeysForDates.add(hallDetails.getHallId() + "|" + date.toString()); - } - - // Check each slot key for locks and manage queues - for (String key : slotKeysForDates) { - System.out.println("Key:" +key); - bookingQueueMap.putIfAbsent(key, new LinkedBlockingQueue<>()); - System.out.println("bookingQueueMap: " + bookingQueueMap.size()); - - - BlockingQueue queue = bookingQueueMap.get(key); - System.out.println("queue: " + queue.size()); - - existingBooking = Optional.ofNullable(bookingCalendarRepository.findByBdateAndHallId(formattedStartDate, hallId1)); - - if (existingBooking.isPresent()) { - System.out.println("Record already exists for the given date and hall. Skipping save."); - bcid = existingBooking.get().getId(); // Use existing record ID - bookingCalendarRepository.updateTempBlocked(bcid, true); - System.out.println("bcid111: "+bcid); - hs.put("bcId", bcid); - } else { - bookingCal.setBdate(formattedStartDate); - bookingCal.setEveningSlot(false); - bookingCal.setHallId(hallId1); - bookingCal.setIs_active(true); - bookingCal.setIs_booked(0); - bookingCal.setIs_delete(false); - bookingCal.setMorningSlot(false); - bookingCal.setIs_blocked(false); - bookingCal.setTemp_blocked(true); - - BookingCalendar bc = bookingCalendarRepository.save(bookingCal); - bcid = bc.getId(); - hs.put("bcId", bcid); - } - - System.out.println("lockedSlots: " + lockedSlots.size()); - // Check if slot is locked - if (lockedSlots.containsKey(key)) { - - //To allow first user in the queue to navigate between the steps - if (!queue.isEmpty() && queue.peek() != userId) { - queueLog.setStartDate(formattedStartDate); - queueLog.setStarting_slot(startingSlot); - queueLog.setEndDate(formattedEndDate); - queueLog.setEnding_slot(endingSlot); - queueLog.setUser_id(userId); - queueLog.setHall_id(hallId1); - queueLog.setSlotKey(key); - - QueueLog ql = queueLogRepository.save(queueLog); - System.out.println("Queue Id: " + ql.getQueue_id()); - - hs.put("status", "slotLocked"); - hs.put("message", "Hall slot is locked by another user. Please wait."); - - return hs; - } - } - - System.out.println("userId: " + userId); - queue.add(userId); - int position = new ArrayList<>(queue).indexOf(userId) + 1; - - if (position > 1) { - hs.put("status", "inQueue"); - hs.put("message", "You are " + position + " in the queue for slot " + key + ". Please wait for your turn."); - return hs; - } - - //lockedSlots.put(slotKey, System.currentTimeMillis() + 10 * 60 * 1000); // 10 minutes lock - lockedSlots.put(key, System.currentTimeMillis() + 3 * 60 * 1000); //3 minute lock - - if (formData.containsKey("bcId") && formData.get("bcId") != null && !formData.get("bcId").toString().trim().isEmpty()) { - finalBcId.set(Integer.parseInt(formData.get("bcId").toString())); - } - - if (!slotTimers.containsKey(key)) { - Timer timer = new Timer(); - slotTimers.put(key, timer); - - timer.schedule(new TimerTask() { - @Override - public void run() { - // Check if lock expired - if (System.currentTimeMillis() > lockedSlots.getOrDefault(key, 0L)) { - - lockedSlots.remove(key); - System.out.println("finalBcId: "+finalBcId); - if(finalBcId.get()!=0) - { - bookingCalendarRepository.updateTempBlocked(finalBcId.get(), false); - } - - // Clear the queue without processing further - if (!queue.isEmpty()) { - System.out.println("Clearing the queue for key: " + key); - queue.clear(); - - } - - // Stop the timer if the queue is empty - if (queue.isEmpty()) { - slotTimers.remove(key); - timer.cancel(); - } - } - } - }, 0, 1000 * 60); // Run every 1 minute - } - } - // Calculate discount based on user type if (usertype.equals("COUNCILLOR") || usertype.equals("PENSIONER") || usertype.equals("GCC_EMPLOYEE") || usertype.equals("PUBLIC")) { discountAmount = (hallAmount * discount) / 100; @@ -722,49 +596,49 @@ public class BookingServiceImpl implements BookingService { reasoncode = ""; // or any default value } hs.put("reasoncode", reasoncode); - HallDetailsConcession governmentevents=hallDetailsConcessionRepo.findbyhallId(hallDetails.getHallId()); + HallDetailsConcession governmentevents = hallDetailsConcessionRepo.findbyhallId(hallDetails.getHallId()); if (reasoncode.equals("SGE")) { - if(startingSlot == 1 && endingSlot == 2) { + if (startingSlot == 1 && endingSlot == 2) { discountAmount = (governmentevents.getFulldayhallamount() * hallDetails.getSGEdiscount()) / 100; hallAmount = governmentevents.getFulldayhallamount(); hs.put("discount", hallDetails.getSGEdiscount()); // No discount for State Govt Event - double cleaningCharges=governmentevents.getFullDayCleaningcharges(); - double PASystem=governmentevents.getFulldayPAsystem(); - double EB=governmentevents.getFulldayEBcharges(); - double additionalcharges = cleaningCharges+PASystem+EB; + double cleaningCharges = governmentevents.getFullDayCleaningcharges(); + double PASystem = governmentevents.getFulldayPAsystem(); + double EB = governmentevents.getFulldayEBcharges(); + double additionalcharges = cleaningCharges + PASystem + EB; double gstAmount = Math.round(additionalcharges * hallDetails.getGst()) / 100.0; double depositAmount = hallDetails.getDepositAmount() * daysrange; - double totalAmount=additionalcharges+gstAmount+depositAmount; - double truncatedTotalAmount=Math.round(totalAmount * 100.0) / 100.0; + double totalAmount = additionalcharges + gstAmount + depositAmount; + double truncatedTotalAmount = Math.round(totalAmount * 100.0) / 100.0; hs.put("actualhallamount", hallAmount); bookingDetails.setDepositAmount(depositeamount); bookingDetails.setHallAmount(additionalcharges); bookingDetails.setGst(gstAmount); bookingDetails.setAmountReceived(truncatedTotalAmount); hs.put("additionalcharges", additionalcharges); - hs.put("totalAmount",truncatedTotalAmount); - }else { + hs.put("totalAmount", truncatedTotalAmount); + } else { hallAmount = governmentevents.getHalfdayhallamount(); discountAmount = (hallAmount * hallDetails.getSGEdiscount()) / 100; hs.put("discount", hallDetails.getSGEdiscount()); // No discount for State Govt Event - double cleaningCharges=governmentevents.getHalfDayCleaningcharges(); - double PASystem=governmentevents.getHalfdayPAsystem(); - double EB=governmentevents.getHalfdayEBcharges(); - double additionalcharges = cleaningCharges+PASystem+EB; + double cleaningCharges = governmentevents.getHalfDayCleaningcharges(); + double PASystem = governmentevents.getHalfdayPAsystem(); + double EB = governmentevents.getHalfdayEBcharges(); + double additionalcharges = cleaningCharges + PASystem + EB; double gstAmount = Math.round(additionalcharges * hallDetails.getGst()) / 100.0; double depositAmount = hallDetails.getDepositAmount() * daysrange; - double totalAmount=additionalcharges+gstAmount+depositAmount; - double truncatedTotalAmount=Math.round(totalAmount * 100.0) / 100.0; + double totalAmount = additionalcharges + gstAmount + depositAmount; + double truncatedTotalAmount = Math.round(totalAmount * 100.0) / 100.0; hs.put("actualhallamount", hallAmount); bookingDetails.setDepositAmount(depositeamount); bookingDetails.setHallAmount(additionalcharges); bookingDetails.setGst(gstAmount); bookingDetails.setAmountReceived(truncatedTotalAmount); hs.put("additionalcharges", additionalcharges); - hs.put("totalAmount",truncatedTotalAmount); + hs.put("totalAmount", truncatedTotalAmount); } - } else if (reasoncode.equals("CGE")) { - /*double hallAmountforcentral = calcHallAmount(hallDetails, daysrange, startingSlot, endingSlot); + } /*else if (reasoncode.equals("CGE")) { + double hallAmountforcentral = calcHallAmount(hallDetails, daysrange, startingSlot, endingSlot); double discountAmounts = (hallAmountforcentral * hallDetails.getCGEdiscount()) / 100; hs.put("discount", hallDetails.getCGEdiscount()); // 50% discount for Central Govt Event hallAmountforcentral = hallAmountforcentral - discountAmounts; @@ -774,7 +648,7 @@ public class BookingServiceImpl implements BookingService { // Truncate the total amount to two decimal places //double truncatedTotalAmount = Math.floor(totalAmount * 100) / 100; - // Round the total amount to two decimal places + // Round the total amount to two decimal places double truncatedTotalAmount = Math.round(totalAmount * 100.0) / 100.0; // Set the calculated amounts to bookingDetails @@ -782,8 +656,8 @@ public class BookingServiceImpl implements BookingService { bookingDetails.setHallAmount(hallAmountforcentral); bookingDetails.setGst(gstAmount); bookingDetails.setAmountReceived(truncatedTotalAmount); - hs.put("totalAmount", truncatedTotalAmount);*/ - + hs.put("totalAmount", truncatedTotalAmount); + }*/ else if (reasoncode.equals("CGE")) { if (startingSlot == 1 && endingSlot == 2) { discountAmount = (hallDetails.getFullDayRent() * hallDetails.getCGEdiscount()) / 100; hallAmount = hallDetails.getFullDayRent(); @@ -800,7 +674,8 @@ public class BookingServiceImpl implements BookingService { double truncatedTotalAmount = Math.round(totalAmount * 100.0) / 100.0; hs.put("actualhallamount", hallAmount); bookingDetails.setDepositAmount(depositeamount); - bookingDetails.setHallAmount(additionalcharges); + //bookingDetails.setHallAmount(additionalcharges); + bookingDetails.setHallAmount(netAmount); bookingDetails.setGst(gstAmount); bookingDetails.setAmountReceived(truncatedTotalAmount); @@ -826,7 +701,8 @@ public class BookingServiceImpl implements BookingService { double truncatedTotalAmount = Math.round(totalAmount * 100.0) / 100.0; hs.put("actualhallamount", hallAmount); bookingDetails.setDepositAmount(depositeamount); - bookingDetails.setHallAmount(additionalcharges); + //bookingDetails.setHallAmount(additionalcharges); + bookingDetails.setHallAmount(netAmount); bookingDetails.setGst(gstAmount); bookingDetails.setAmountReceived(truncatedTotalAmount); @@ -839,6 +715,7 @@ public class BookingServiceImpl implements BookingService { } } + bookingDetails.setNoOfDays(days); bookingDetails.setStartingSlot(startingSlot); bookingDetails.setEndingSlot(endingSlot); @@ -846,25 +723,43 @@ public class BookingServiceImpl implements BookingService { bookingDetails.setEndDate(endDate); bookingDetails.setBookingDate(LocalDate.now()); bookingDetails.setReason(reasonMaster.getReason()); - bookingDetails.setRefundStatus(RefundStatus.WAITING); + bookingDetails.setRefundStatus(BookingDetails.RefundStatus.WAITING); bookingDetails.setComments("Booking Slot not Confirmed."); bookingDetails.setBookingtype(BookingDetails.BookingType.ONLINE); bookingDetails.setRelationship(relation); - boolean slotStatus = isSlotOccupied(bookingDetails); - System.out.println("slotStatus: "+slotStatus); - if(slotStatus){ - return Collections.singletonMap("status", "slotOccupied"); + int i = 0; + String startDateStr = bookingDetails.getStartDate(); + String endDateStr = bookingDetails.getEndDate(); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + LocalDate start = LocalDate.parse(startDateStr, formatter); + LocalDate end = LocalDate.parse(endDateStr, formatter); + int hallId = bookingDetails.getHallDetails().getHallId(); + + for (LocalDate date = start; !date.isAfter(end); date = date.plusDays(1)) { + BookingCalendar bookingCalendar = bookingCalendarRepository.findByBdateAndHallId(date, hallId); + + if (bookingCalendar != null) { + if ((date.equals(start) && bookingDetails.getStartingSlot() == 1 && bookingCalendar.isMorningSlot()) || + (date.equals(start) && bookingDetails.getStartingSlot() == 2 && bookingCalendar.isEveningSlot()) || + (date.equals(end) && bookingDetails.getEndingSlot() == 1 && bookingCalendar.isMorningSlot()) || + (date.equals(end) && bookingDetails.getEndingSlot() == 2 && bookingCalendar.isEveningSlot())) { + return Collections.singletonMap("status", "slotOccupied"); + } else if (bookingCalendar.isMorningSlot() && bookingCalendar.isEveningSlot()) { + return Collections.singletonMap("status", "slotOccupied"); + } else if (!date.equals(end) && i != 0 && i != Math.round(bookingDetails.getNoOfDays() - 1) + && (bookingCalendar.isMorningSlot() || bookingCalendar.isEveningSlot())) { + return Collections.singletonMap("status", "slotOccupied"); + } else if (date.equals(end) && bookingDetails.getEndingSlot() == 2 && bookingCalendar.isMorningSlot() + && i != 0 && i == Math.round(bookingDetails.getNoOfDays() - 1)) { + return Collections.singletonMap("status", "slotOccupied"); + } + } + i++; } // Save the booking details after the loop - try{ - bookingDetails = bookingDetailsRepository.save(bookingDetails); - }catch(Exception e) - { - System.out.println("Exception:"+e.getMessage()); - return Collections.singletonMap("status", "slotOccupiedbyAnotherUser"); - } + bookingDetails = bookingDetailsRepository.save(bookingDetails); // confirmation of amount hs.put("bookingId", bookingDetails.getBookingId()); @@ -919,44 +814,7 @@ public class BookingServiceImpl implements BookingService { return hs; } - public boolean isSlotOccupied(BookingDetails bookingDetails) { - - // Slot occupied logic - int i = 0; - String startDateStr = bookingDetails.getStartDate(); - String endDateStr = bookingDetails.getEndDate(); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); - LocalDate start = LocalDate.parse(startDateStr, formatter); - LocalDate end = LocalDate.parse(endDateStr, formatter); - int hallId = bookingDetails.getHallDetails().getHallId(); - - for (LocalDate date = start; !date.isAfter(end); date = date.plusDays(1)) { - BookingCalendar bookingCalendar = bookingCalendarRepository.findByBdateAndHallId(date, hallId); - - if (bookingCalendar != null) { - if ((date.equals(start) && bookingDetails.getStartingSlot() == 1 && bookingCalendar.isMorningSlot()) || - (date.equals(start) && bookingDetails.getStartingSlot() == 2 && bookingCalendar.isEveningSlot()) || - (date.equals(end) && bookingDetails.getEndingSlot() == 1 && bookingCalendar.isMorningSlot()) || - (date.equals(end) && bookingDetails.getEndingSlot() == 2 && bookingCalendar.isEveningSlot())) { - return true; - } else if (bookingCalendar.isMorningSlot() && bookingCalendar.isEveningSlot()) { - return true; - } else if (!date.equals(end) && i != 0 && i != Math.round(bookingDetails.getNoOfDays() - 1) - && (bookingCalendar.isMorningSlot() || bookingCalendar.isEveningSlot())) { - return true; - } else if (date.equals(end) && bookingDetails.getEndingSlot() == 2 && bookingCalendar.isMorningSlot() - && i != 0 && i == Math.round(bookingDetails.getNoOfDays() - 1)) { - return true; - } - } - i++; - } - - return false; - - } - - private double calcHallAmount(HallDetails hallDetails, int daysrange,int startPeriod, int endPeriod) { + private double calcHallAmount(HallDetails hallDetails, int daysrange, int startPeriod, int endPeriod) { double hallAmount = 0; if (daysrange == 1) { if (startPeriod == 1 && endPeriod == 2) { @@ -977,18 +835,18 @@ public class BookingServiceImpl implements BookingService { } else if (startPeriod == 2 && endPeriod == 2) { hallAmount = hallDetails.getFullDayRent() * (daysrange - 1) + hallDetails.getHalfDayRent(); } else if (startPeriod == 2 && endPeriod == 1) { - hallAmount = hallDetails.getFullDayRent() * (daysrange - 2) + hallDetails.getHalfDayRent()*2; + hallAmount = hallDetails.getFullDayRent() * (daysrange - 2) + hallDetails.getHalfDayRent() * 2; } } return hallAmount; } - + public String uploadNOCFile(MultipartFile file, int bookingId) { // Retrieve booking details, throw an exception if not found BookingDetails bookingDetails = bookingDetailsRepository.findById(bookingId) .orElseThrow(() -> new IllegalArgumentException("Invalid booking ID: " + bookingId)); - String reason = "NOC"; + String reason = "NOC"; String fileName = bookingId + "_" + file.getOriginalFilename(); String fileUrl = serverPath + "images/" + reason + "/" + fileName; String filePath = uploadDirectory + File.separator + reason + File.separator + fileName; @@ -998,7 +856,7 @@ public class BookingServiceImpl implements BookingService { if (!directory.exists()) { directory.mkdirs(); // Create the directory if it doesn't exist } - BookingHistory bookinghistory=new BookingHistory(); + BookingHistory bookinghistory = new BookingHistory(); bookinghistory.setBookingStatus(bookingDetails.getBookingStatus()); bookinghistory.setBookingDetails(bookingDetails); bookinghistory.setStartDate(bookingDetails.getStartDate()); @@ -1027,11 +885,11 @@ public class BookingServiceImpl implements BookingService { // Save the document details in the repository bookingDetailsRepository.save(bookingDetails); bookingDocumentsRepository.save(bd); - + return "File uploaded and saved successfully"; } - + @Transactional public List saveGCCBlockingDate(GccBlockingDate gcc) { // Save the GccBlockingDate first @@ -1053,23 +911,23 @@ public class BookingServiceImpl implements BookingService { // Create and save BookingDetails BookingDetails bookingDetails = new BookingDetails(); - bookingDetails.setBookingStatus(BookingStatus.GCC_BLOCKED); + bookingDetails.setBookingStatus(BookingDetails.BookingStatus.GCC_BLOCKED); bookingDetails.setReason(gcc.getBlockingReason()); bookingDetails.setNoOfDays(0); bookingDetails.setAmountReceived(0); bookingDetails.setDepositAmount(0); - bookingDetails.setRefundStatus(RefundStatus.NA); + bookingDetails.setRefundStatus(BookingDetails.RefundStatus.NA); bookingDetails.setBookingDate(LocalDate.now()); bookingDetails.setStartDate(LocalDate.ofInstant(savedGcc.getStartDate().toInstant(), ZoneId.systemDefault()).format(formatter)); bookingDetails.setEndDate(LocalDate.ofInstant(savedGcc.getEndDate().toInstant(), ZoneId.systemDefault()).format(formatter)); bookingDetails.setHallAmount(0); bookingDetails.setHallDetails(hallDetails); bookingDetails.setUsers(user); - + bookingDetails = bookingDetailsRepository.save(bookingDetails); bookingIds.add(bookingDetails.getBookingId()); - //System.out.println("BookingDetails saved with ID: " + bookingDetails.getBookingId()); + System.out.println("BookingDetails saved with ID: " + bookingDetails.getBookingId()); } // Save the list of booking IDs in the GccBlockingDate entity @@ -1084,146 +942,150 @@ public class BookingServiceImpl implements BookingService { } public List getCancelling(String fromDate, String toDate, String hallID) { - List data = bookingCalendarRepository.getCancelling(fromDate, toDate, hallID); - return data; - } + List data = bookingCalendarRepository.getCancelling(fromDate, toDate, hallID); + return data; + } public BookingCalendar getbyDates(LocalDate aa, String hallID) { - BookingCalendar data = bookingCalendarRepository.getbyDates(aa, hallID); - return data; - } + BookingCalendar data = bookingCalendarRepository.getbyDates(aa, hallID); + return data; + } public void updateBookingStatus(BookingCalendar book) { - bookingCalendarRepository.save(book); - } + bookingCalendarRepository.save(book); + + } public List getCancellingdata1(String bookID) { - List data = bookingCalendarRepository.getCancellingdata1(bookID); - return data; - } + List data = bookingCalendarRepository.getCancellingdata1(bookID); + return data; + } //caretaker @Override - public List getPresentsEventsByUserId(Integer hallId) { - // TODO Auto-generated method stub - return bookingDetailsRepository.findPresentsEventsByUserId(hallId); - } - public List getSettlementList(Integer hallId) { - // TODO Auto-generated method stub - return bookingDetailsRepository.getSettlementList(hallId); - } - - @Override - public List getPastsEventsByUserId(Integer hallId) { - // TODO Auto-generated method stub - return bookingDetailsRepository.findPastEventsByHallId(hallId); - } - - @Override - public List getFuturesEventsByUserId(Integer hallId) { - // TODO Auto-generated method stub - return bookingDetailsRepository.findFutureEventsByHallId(hallId); - } - @Override - public List getFilteredBookings(LocalDate fromDate, LocalDate toDate, List hallIds) { - return bookingDetailsRepository.findByFromDateBetweenAndToDateBetweenAndHallIdIn(fromDate, toDate, hallIds); - } - - @Override - public List getBlockedEvents(LocalDate fromDate, LocalDate toDate, List hallIds) { - return blockingDateRepository.findByFromDateAndToDateBetweenAndHallIdIn(fromDate, toDate, hallIds); - } - - @Override - public BookingDetails updateBookingStatustoGCCBlocked(BookingDetails bookingDetails) { - BookingDetails save = bookingDetailsRepository.save(bookingDetails); - return save; - } - //carearetakerend - - - @Override - public BookingDetails updateBookingStatusById(int bookingId, BookingStatus status, String comments) { - Optional bookingDetails = bookingDetailsRepository.findById(bookingId); - if (bookingDetails.isPresent()) { - BookingDetails bookDet = bookingDetails.get(); - // Update Booking Status - bookDet.setBookingStatus(status); - bookDet.setComments(comments); - BookingDetails updatedBookingDetails = bookingDetailsRepository.save(bookDet); - return updatedBookingDetails; - } - return null; - } - - @Override - public BookingDetails updateCancelledBookingStatus(int bookingId, BookingStatus status, String comments) { - Optional bookingDetails = bookingDetailsRepository.findById(bookingId); - if (bookingDetails.isPresent()) { - BookingDetails bookDet = bookingDetails.get(); - // System.out.println("Current booking status: " + bookDet.getBookingStatus()); - - // Create Booking History Entry - BookingHistory bookHistory = new BookingHistory(); - bookHistory.setBookingDetails(bookDet); - bookHistory.setBookingStatus(bookDet.getBookingStatus()); - bookHistory.setStartDate(bookDet.getStartDate()); - bookHistory.setEndDate(bookDet.getEndDate()); - bookHistory.setComments(bookDet.getComments()); - bookHistory.setCdate(new Date()); - bookHistory.setRefundStatus(bookDet.getRefundStatus()); - bookingHistoryRepository.save(bookHistory); - // Update Booking Status - bookDet.setBookingStatus(status); - bookDet.setComments(comments); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); - String formattedDate = LocalDateTime.now().format(formatter); - bookDet.setUpdatedDate(formattedDate); - BookingDetails updatedBookingDetails = bookingDetailsRepository.save(bookDet); - List bookingCalendarList = bookingCalendarRepository.getCancellingdata1(String.valueOf(bookDet.getBookingId())); - - for (BookingCalendar calendar : bookingCalendarList) { - - if (String.valueOf(bookDet.getBookingId()).equals(calendar.getBookingId_1())) { - calendar.setBookingId_1(null); - calendar.setMorningSlot(false); - } - if (String.valueOf(bookDet.getBookingId()).equals(calendar.getBookingId_2())) { - calendar.setBookingId_2(null); - calendar.setEveningSlot(false); - } - bookingCalendarRepository.save(calendar); - - } - return updatedBookingDetails; - } - //System.out.println("Booking details not found for ID: " + bookingId); - return null; - } - - @Override - public EbDetails updateEbDetails(int bookingId,double startUnit,double endUnit,char status) { - Optional bookingDetails= bookingDetailsRepository.findById(bookingId); - if(bookingDetails.isPresent()){ + public List getPresentsEventsByUserId(Integer hallId) { + // TODO Auto-generated method stub + return bookingDetailsRepository.findPresentsEventsByUserId(hallId); + } + + public List getSettlementList(Integer hallId) { + // TODO Auto-generated method stub + return bookingDetailsRepository.getSettlementList(hallId); + } + + @Override + public List getPastsEventsByUserId(Integer hallId) { + // TODO Auto-generated method stub + return bookingDetailsRepository.findPastEventsByHallId(hallId); + } + + @Override + public List getFuturesEventsByUserId(Integer hallId) { + // TODO Auto-generated method stub + return bookingDetailsRepository.findFutureEventsByHallId(hallId); + } + + @Override + public List getFilteredBookings(LocalDate fromDate, LocalDate toDate, List hallIds) { + return bookingDetailsRepository.findByFromDateBetweenAndToDateBetweenAndHallIdIn(fromDate, toDate, hallIds); + } + + @Override + public List getBlockedEvents(LocalDate fromDate, LocalDate toDate, List hallIds) { + return blockingDateRepository.findByFromDateAndToDateBetweenAndHallIdIn(fromDate, toDate, hallIds); + } + + @Override + public BookingDetails updateBookingStatustoGCCBlocked(BookingDetails bookingDetails) { + BookingDetails save = bookingDetailsRepository.save(bookingDetails); + return save; + } + //carearetakerend + + + @Override + public BookingDetails updateBookingStatusById(int bookingId, BookingDetails.BookingStatus status, String comments) { + Optional bookingDetails = bookingDetailsRepository.findById(bookingId); + if (bookingDetails.isPresent()) { + BookingDetails bookDet = bookingDetails.get(); + // Update Booking Status + bookDet.setBookingStatus(status); + bookDet.setComments(comments); + BookingDetails updatedBookingDetails = bookingDetailsRepository.save(bookDet); + return updatedBookingDetails; + } + return null; + } + + @Override + public BookingDetails updateCancelledBookingStatus(int bookingId, BookingDetails.BookingStatus status, String comments) { + Optional bookingDetails = bookingDetailsRepository.findById(bookingId); + if (bookingDetails.isPresent()) { + BookingDetails bookDet = bookingDetails.get(); + // System.out.println("Current booking status: " + bookDet.getBookingStatus()); + + // Create Booking History Entry + BookingHistory bookHistory = new BookingHistory(); + bookHistory.setBookingDetails(bookDet); + bookHistory.setBookingStatus(bookDet.getBookingStatus()); + bookHistory.setStartDate(bookDet.getStartDate()); + bookHistory.setEndDate(bookDet.getEndDate()); + bookHistory.setComments(bookDet.getComments()); + bookHistory.setCdate(new Date()); + bookHistory.setRefundStatus(bookDet.getRefundStatus()); + bookingHistoryRepository.save(bookHistory); + // Update Booking Status + bookDet.setBookingStatus(status); + bookDet.setComments(comments); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + String formattedDate = LocalDateTime.now().format(formatter); + bookDet.setUpdatedDate(formattedDate); + BookingDetails updatedBookingDetails = bookingDetailsRepository.save(bookDet); + List bookingCalendarList = bookingCalendarRepository.getCancellingdata1(String.valueOf(bookDet.getBookingId())); + + for (BookingCalendar calendar : bookingCalendarList) { + + if (String.valueOf(bookDet.getBookingId()).equals(calendar.getBookingId_1())) { + calendar.setBookingId_1(null); + calendar.setMorningSlot(false); + } + if (String.valueOf(bookDet.getBookingId()).equals(calendar.getBookingId_2())) { + calendar.setBookingId_2(null); + calendar.setEveningSlot(false); + } + bookingCalendarRepository.save(calendar); + + } + return updatedBookingDetails; + } + //System.out.println("Booking details not found for ID: " + bookingId); + return null; + } + + @Override + public EbDetails updateEbDetails(int bookingId, double startUnit, double endUnit, char status) { + Optional bookingDetails = bookingDetailsRepository.findById(bookingId); + if (bookingDetails.isPresent()) { BookingDetails bd = bookingDetails.get(); EbDetails ed = bd.getEbDetails(); - if(ed==null){ - ed= new EbDetails(); + if (ed == null) { + ed = new EbDetails(); ed.setBookingDetails(bd); } - if(status=='S') { + if (status == 'S') { ed.setCdate(new Date()); ed.setStartingReading(startUnit); return ebDetailsRepository.save(ed); - } else if (status=='E') { + } else if (status == 'E') { double startReading = ed.getStartingReading(); - if(endUnit != 0 ){ + if (endUnit != 0) { ed.setEndingReading(endUnit); - double usedUnit= endUnit - startReading; - ed.setUsedUnit(Float.parseFloat(usedUnit+"")); + double usedUnit = Math.floor((endUnit - startReading) * 100) / 100.0; + ed.setUsedUnit(Float.parseFloat(usedUnit + "")); float costPerUnit = bd.getHallDetails().getEbCostPerUnit(); - ed.setEbAmount(usedUnit * costPerUnit); + double ebAmount = Math.floor((usedUnit * costPerUnit) * 100) / 100.0; + ed.setEbAmount(ebAmount); ed.setUpdatedDate(new Date()); return ebDetailsRepository.save(ed); } @@ -1233,103 +1095,103 @@ public class BookingServiceImpl implements BookingService { } @Override - public String cancelBooking(int bookingId, BookingStatus currentStatus,String comments) { - Optional bd =bookingDetailsRepository.findById(bookingId); - if(bd.isPresent()){ + public String cancelBooking(int bookingId, BookingDetails.BookingStatus currentStatus, String comments) { + Optional bd = bookingDetailsRepository.findById(bookingId); + if (bd.isPresent()) { BookingDetails bookingDetails = bd.get(); //System.out.println("currentStatus:-"+currentStatus); - if(bookingDetails.getBookingStatus().equals(BookingStatus.APPROVED)){ - //System.err.println("test"+currentStatus); - if(currentStatus.equals(BookingStatus.CANCELED)){ - //System.err.println("test11"+currentStatus); - try{ - //System.err.println("test13331==="+currentStatus); - applicationLogService.saveLog(bookingDetails.getBookingId(),ApplicationLogs.logsOfMsg.USER_CANCELLED_BOOKING.toString(),comments); - String refundTheDepositAmount = paymentGatewayService.refundTheDepositAmount(bookingDetails.getBookingId(),bookingDetails.getUsers().getUserId(),bookingDetails.getDepositAmount()); + if (bookingDetails.getBookingStatus().equals(BookingDetails.BookingStatus.APPROVED)) { + //System.err.println("test"+currentStatus); + if (currentStatus.equals(BookingDetails.BookingStatus.CANCELED)) { + //System.err.println("test11"+currentStatus); + try { + //System.err.println("test13331==="+currentStatus); + applicationLogService.saveLog(bookingDetails.getBookingId(), ApplicationLogs.logsOfMsg.USER_CANCELLED_BOOKING.toString(), comments); + String refundTheDepositAmount = paymentGatewayService.refundTheDepositAmount(bookingDetails.getBookingId(), bookingDetails.getUsers().getUserId(), bookingDetails.getDepositAmount()); //System.out.println("refundTheDepositAmount==="+refundTheDepositAmount); - if(refundTheDepositAmount.equals("Refunded")) { - updateBookingStatusById(bookingDetails.getBookingId(), BookingStatus.CANCELED,"user cancelled Date:-"+new Date()); - - List bookingCalendarList = bookingCalendarRepository.getCancellingdata1(String.valueOf(bookingDetails.getBookingId())); - - for (BookingCalendar calendar : bookingCalendarList) { - boolean isUpdated = false; - - if (String.valueOf(bookingDetails.getBookingId()).equals(calendar.getBookingId_1())) { - calendar.setBookingId_1(null); - isUpdated = true; - } - if (String.valueOf(bookingDetails.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); - } - } - return "success"; + if (refundTheDepositAmount.equals("Refunded")) { + updateBookingStatusById(bookingDetails.getBookingId(), BookingDetails.BookingStatus.CANCELED, "user cancelled Date:-" + new Date()); + + List bookingCalendarList = bookingCalendarRepository.getCancellingdata1(String.valueOf(bookingDetails.getBookingId())); + + for (BookingCalendar calendar : bookingCalendarList) { + boolean isUpdated = false; + + if (String.valueOf(bookingDetails.getBookingId()).equals(calendar.getBookingId_1())) { + calendar.setBookingId_1(null); + isUpdated = true; + } + if (String.valueOf(bookingDetails.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); + } + } + return "success"; } return "error"; - }catch (Exception e){ + } catch (Exception e) { e.printStackTrace(); } - } else if (currentStatus.equals(BookingStatus.REJECTED)) { - try{ - applicationLogService.saveLog(bookingDetails.getBookingId(),ApplicationLogs.logsOfMsg.GCC_REJECTED.toString(),comments); - String refundtheAmount=paymentGatewayService.refundTheAmount(bookingDetails.getBookingId(),bookingDetails.getUsers().getUserId()); + } else if (currentStatus.equals(BookingDetails.BookingStatus.REJECTED)) { + try { + applicationLogService.saveLog(bookingDetails.getBookingId(), ApplicationLogs.logsOfMsg.GCC_REJECTED.toString(), comments); + String refundtheAmount = paymentGatewayService.refundTheAmount(bookingDetails.getBookingId(), bookingDetails.getUsers().getUserId()); //System.out.println("refundtheAmount==="+refundtheAmount); - if(refundtheAmount.equals("Refunded")) { - updateBookingStatusById(bookingDetails.getBookingId(), BookingStatus.REJECTED,comments); - - List bookingCalendarList = bookingCalendarRepository.getCancellingdata1(String.valueOf(bookingDetails.getBookingId())); - - for (BookingCalendar calendar : bookingCalendarList) { - boolean isUpdated = false; - - if (String.valueOf(bookingDetails.getBookingId()).equals(calendar.getBookingId_1())) { - calendar.setBookingId_1(null); - isUpdated = true; - } - if (String.valueOf(bookingDetails.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); - } - } - return "success"; + if (refundtheAmount.equals("Refunded")) { + updateBookingStatusById(bookingDetails.getBookingId(), BookingDetails.BookingStatus.REJECTED, comments); + + List bookingCalendarList = bookingCalendarRepository.getCancellingdata1(String.valueOf(bookingDetails.getBookingId())); + + for (BookingCalendar calendar : bookingCalendarList) { + boolean isUpdated = false; + + if (String.valueOf(bookingDetails.getBookingId()).equals(calendar.getBookingId_1())) { + calendar.setBookingId_1(null); + isUpdated = true; + } + if (String.valueOf(bookingDetails.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); + } + } + return "success"; } return "error"; - }catch (Exception e){ + } catch (Exception e) { e.printStackTrace(); } - } else if (currentStatus.equals(BookingStatus.GCC_BLOCKED)) { - try{ - applicationLogService.saveLog(bookingDetails.getBookingId(),ApplicationLogs.logsOfMsg.GCC_BLOCKED_DATE.toString(),comments); - paymentGatewayService.refundTheAmount(bookingDetails.getBookingId(),bookingDetails.getUsers().getUserId()); - updateBookingStatusById(bookingDetails.getBookingId(), BookingStatus.GCC_BLOCKED, "total amount will refund shortly"); - }catch (Exception e){ + } else if (currentStatus.equals(BookingDetails.BookingStatus.GCC_BLOCKED)) { + try { + applicationLogService.saveLog(bookingDetails.getBookingId(), ApplicationLogs.logsOfMsg.GCC_BLOCKED_DATE.toString(), comments); + paymentGatewayService.refundTheAmount(bookingDetails.getBookingId(), bookingDetails.getUsers().getUserId()); + updateBookingStatusById(bookingDetails.getBookingId(), BookingDetails.BookingStatus.GCC_BLOCKED, "total amount will refund shortly"); + } catch (Exception e) { e.printStackTrace(); } @@ -1340,160 +1202,164 @@ public class BookingServiceImpl implements BookingService { } return null; } - + @Override public BookingDetails getBookingDetailsWithSettlement(int settlementId) { - Optional SettleBookingDetails =Optional.of(bookingDetailsRepository.findBySettlementIdWithBookingDetails(settlementId)); - if(SettleBookingDetails.isPresent()) { + Optional SettleBookingDetails = Optional.of(bookingDetailsRepository.findBySettlementIdWithBookingDetails(settlementId)); + if (SettleBookingDetails.isPresent()) { return SettleBookingDetails.get(); } return null; } + @Override - public BookingDetails saveebdetails(int bookingId, double startingReading, - MultipartFile startingReadingimage) { - BookingDetails bd =getBookingsById(bookingId); - if (bd != null) { - if (bd.getEbDetails() == null) { - EbDetails eb = new EbDetails(); - eb.setCdate(new Date()); - eb.setStartingReading(startingReading); - if(startingReadingimage!=null) { - eb.setEbImageUrl((serverPath+"images/eb/"+bookingId+"_"+startingReadingimage.getOriginalFilename())); - String filePath =uploadDirectory+"/eb/"+bookingId+"_"+startingReadingimage.getOriginalFilename(); - try(FileOutputStream fos = new FileOutputStream(filePath)){ - byte [] bytes = startingReadingimage.getBytes(); + public BookingDetails saveebdetails(int bookingId, double startingReading, + MultipartFile startingReadingimage) { + BookingDetails bd = getBookingsById(bookingId); + if (bd != null) { + if (bd.getEbDetails() == null) { + EbDetails eb = new EbDetails(); + eb.setCdate(new Date()); + eb.setStartingReading(startingReading); + if (startingReadingimage != null) { + eb.setEbImageUrl((serverPath + "images/eb/" + bookingId + "_" + startingReadingimage.getOriginalFilename())); + String filePath = uploadDirectory + "/eb/" + bookingId + "_" + startingReadingimage.getOriginalFilename(); + try (FileOutputStream fos = new FileOutputStream(filePath)) { + byte[] bytes = startingReadingimage.getBytes(); + fos.write(bytes); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + eb.setBookingDetails(bd); + bd.setEbDetails(eb); + return bd; + } + } + return null; + } + + @Override + public String processEbDetailsAndDamage(int bookingId, int ebId, double startingReading, double endingReading, + float usedUnit, double ebAmount, String[] assetNames, String[] comments, int[] quantities, + Double[] assetAmounts, MultipartFile[] assetImages) { + Optional findById = bookingDetailsRepository.findById(bookingId); + if (findById.isPresent()) { + BookingDetails book = findById.get(); + book.setRefundStatus(RefundStatus.WAITING); + EbDetails updateEbDetails = updateEbDetails(bookingId, startingReading, endingReading, 'E'); + double damageAmount = 0; + String adminname = (String) session.getAttribute("usertype"); + if (assetNames != null && assetNames.length > 0) { + for (int i = 0; i < assetNames.length; i++) { + Damage damage = new Damage(); + damage.setAssetName(assetNames[i]); + damage.setComments(comments[i]); + damage.setQuantity(quantities[i]); + damage.setAssetAmount(assetAmounts[i]); + damage.setUpdatedBy(adminname); + damage.setHallDetails(book.getHallDetails()); + damageAmount = damageAmount + assetAmounts[i]; + if (assetImages != null && !assetImages[i].isEmpty()) { + damage.setDamageImageUrl(serverPath + "images/damage/" + bookingId + "_" + assetImages[i].getOriginalFilename()); + String filePath = uploadDirectory + "/damage/" + bookingId + "_" + assetImages[i].getOriginalFilename(); + try (FileOutputStream fos = new FileOutputStream(filePath)) { + byte[] bytes = assetImages[i].getBytes(); fos.write(bytes); } catch (Exception e) { throw new RuntimeException(e); } - } - eb.setBookingDetails(bd); - bd.setEbDetails(eb); - return bd; - } - } - return null; - } - @Override - public String processEbDetailsAndDamage(int bookingId, int ebId, double startingReading, double endingReading, - float usedUnit, double ebAmount, String[] assetNames, String[] comments, int[] quantities, - Double[] assetAmounts, MultipartFile[] assetImages) { - Optional findById = bookingDetailsRepository.findById(bookingId); - if(findById.isPresent()) { - BookingDetails book = findById.get(); - book.setRefundStatus(RefundStatus.WAITING); - EbDetails updateEbDetails = updateEbDetails(bookingId,startingReading,endingReading,'E'); - double damageAmount =0; - String adminname = (String) session.getAttribute("usertype"); - if(assetNames!=null && assetNames.length>0) { - for(int i=0;i getPastData(int hall_id) { - Listdata=bookingCalendarRepository.getPastData(hall_id); - return data; - } - - @Override - public int checkUserBookinglimitation(int userId) { - // TODO Auto-generated method stub - return bookingDetailsRepository.checkUserBookinglimitation(userId); - } - @Override - public List getAllBookingsByUserId(Integer userId) { - // TODO Auto-generated method stub - return bookingDetailsRepository.getAllBookingsByUserId(userId); - } - - public BookingDetails getByBookingId(String bookID) { - - return bookingDetailsRepository.getByBookingId(bookID); - } - - public void updateBookingDetailsStatus(BookingDetails bookingDetails) { - bookingDetailsRepository.save(bookingDetails); - - } - - @Override - public List getBookingUserDetailsReport(String fromDate, String toDate) { - // TODO Auto-generated method stub - return bookingDetailsRepository.getBookingUserDetailsReport(fromDate, toDate); - } - - @Override - public List getBookingHallDetailsReport(String fromDate, String toDate) { - // TODO Auto-generated method stub - return bookingDetailsRepository.getBookingHallDetailsReport(fromDate, toDate); - } - - public List> getAllBookingEventsByUserId(Integer userId) { + } + damage.setBookingDetails(book); + damageRepository.save(damage); + + } + + } + Settlement settlement; + if (book.getSettlement() != null) { + settlement = book.getSettlement(); // Update existing settlement + } else { + settlement = new Settlement(); // Create new settlement + } + settlement.setCdate(LocalDate.now()); + settlement.setBookingDetails(book); + settlement.setDepositAmount(book.getDepositAmount()); + settlement.setEbAmount(updateEbDetails.getEbAmount()); + settlement.setDamageAmount(damageAmount); + settlement.setUpdatedId(adminname); + double refundamount = book.getDepositAmount() - (updateEbDetails.getEbAmount() + damageAmount); + if (refundamount < 0) { + settlement.setRefundedAmount(0); + settlement.setCollectionPending(Math.abs(refundamount)); + settlement.setCollectionStatus("waiting"); + } else { + settlement.setRefundedAmount(refundamount); + settlement.setCollectionPending(0); + } + settlementRepository.save(settlement); + return "Success"; + } + + return "Error"; + } + + //sreeja + @Override + public List getPastData(int hall_id) { + List data = bookingCalendarRepository.getPastData(hall_id); + return data; + } + + @Override + public int checkUserBookinglimitation(int userId) { + // TODO Auto-generated method stub + return bookingDetailsRepository.checkUserBookinglimitation(userId); + } + + @Override + public List getAllBookingsByUserId(Integer userId) { + // TODO Auto-generated method stub + return bookingDetailsRepository.getAllBookingsByUserId(userId); + } + + public BookingDetails getByBookingId(String bookID) { + + return bookingDetailsRepository.getByBookingId(bookID); + } + + public void updateBookingDetailsStatus(BookingDetails bookingDetails) { + bookingDetailsRepository.save(bookingDetails); + + } + + @Override + public List getBookingUserDetailsReport(String fromDate, String toDate) { + // TODO Auto-generated method stub + return bookingDetailsRepository.getBookingUserDetailsReport(fromDate, toDate); + } + + @Override + public List getBookingHallDetailsReport(String fromDate, String toDate) { + // TODO Auto-generated method stub + return bookingDetailsRepository.getBookingHallDetailsReport(fromDate, toDate); + } + + public List> getAllBookingEventsByUserId(Integer userId) { return bookingDetailsRepository.getAllBookingEventsByUserId(userId); } - - //counter - public List> getOfflineBookings() { + + //counter + public List> getOfflineBookings() { return bookingDetailsRepository.findAllByBookingType(); } - @Override - public List getBookedslots(LocalDate fromDate,LocalDate endDate, List hallIdList) { - return bookingCalendarRepository.findByHallIdAndDateRange(fromDate,endDate, hallIdList); + @Override + public List getBookedslots(LocalDate fromDate, LocalDate endDate, List hallIdList) { + return bookingCalendarRepository.findByHallIdAndDateRange(fromDate, endDate, hallIdList); } -// public List processRefundRequests(List bookingIds) { + + // public List processRefundRequests(List bookingIds) { // List bookIds = new ArrayList<>(); // // for (String bookingIdStr : bookingIds) { @@ -1522,115 +1388,115 @@ public class BookingServiceImpl implements BookingService { // private final ConcurrentHashMap processingMap = new ConcurrentHashMap<>(); // // @Synchronized - public String processRefundRequest(int bookingId) { - try { - Optional bookingOptional = bookingDetailsRepository.findById(bookingId); - if (bookingOptional.isPresent()) { - BookingDetails bookingDetails = bookingOptional.get(); - boolean refundSuccess = SettlementAmountRefund(bookingDetails); - if (refundSuccess) { - return "Refund successful for Booking ID: " + bookingId; - } else { - return "Refund failed for Booking ID: " + bookingId; - } - } else { - return "Booking not found for Booking ID: " + bookingId; - } - } catch (Exception e) { - e.printStackTrace(); - return "An error occurred while processing Booking ID: " + bookingId + ": " + e.getMessage(); - } - } - - - public boolean SettlementAmountRefund(BookingDetails bookingDetails) throws Exception { - BookingStatus bookingStatus = bookingDetails.getBookingStatus(); - RefundStatus refunStatus = bookingDetails.getRefundStatus(); - String adminname = (String) session.getAttribute("usertype"); - if (bookingStatus == BookingStatus.APPROVED && !(refunStatus==RefundStatus.COMPLETED) && !(refunStatus==RefundStatus.CLOSED)) { - applicationLogService.saveLog(bookingDetails.getBookingId(), ApplicationLogs.logsOfMsg.SETTLEMENT_COMPLETED.toString(), "Refund will happen shortly"); - String refundThesettlementAmount = paymentGatewayService.refundTheDepositAmount(bookingDetails.getBookingId(), bookingDetails.getUsers().getUserId(),bookingDetails.getSettlement().getRefundedAmount()); - //System.out.println("refundThesettlementAmount === " + refundThesettlementAmount); - if (refundThesettlementAmount.equals("Refunded")) { - Optional book=bookingDetailsRepository.findById(bookingDetails.getBookingId()); - BookingDetails bookings=book.get(); - //bookinghistoty update - BookingHistory bookingHistory=new BookingHistory(); - bookingHistory.setStartDate(bookingDetails.getStartDate()); - bookingHistory.setEndDate(bookingDetails.getEndDate()); - bookingHistory.setComments(bookingDetails.getComments()); - bookingHistory.setBookingDetails(bookingDetails); - bookingHistory.setBookingStatus(bookingDetails.getBookingStatus()); - bookingHistory.setUpdatedBy(adminname); - bookingHistory.setCdate(new Date()); - bookingHistory.setRefundStatus(bookingDetails.getRefundStatus()); - bookingDetails.setComments("Completed the Refund"); - bookingHistoryRepository.save(bookingHistory); - bookings.setBookingStatus(bookingStatus.COMPLETED); - bookings.setRefundStatus(RefundStatus.COMPLETED); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); - String formattedDate = LocalDateTime.now().format(formatter); - bookings.setUpdatedDate(formattedDate); - bookings.setApprovedBy(adminname); - bookingDetailsRepository.save(bookings); - String settlementrefundsms="Your refund amount of Rs. "+bookings.getSettlement().getRefundedAmount()+" for Booking ID "+bookings.getBookingId()+" has been initiated. The amount will be credited to your account within 3 to 15 days. Thanks for using the GCC Community Hall Booking System."; - String settlementrefundurlString ="https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to="+bookings.getUsers().getMobileNo()+"&from=GCCCRP&body="+settlementrefundsms+"&entityid=1401572690000011081&templateid=1407172346804951524"; - String settlementrefundwhatsupmsg="https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to="+bookingDetails.getUsers().getMobileNo()+"&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+refund+of+Rs.+"+bookingDetails.getSettlement().getRefundedAmount()+"+for+Booking+ID+"+bookingDetails.getBookingId()+"+has+been+initiated.+%0AThe+amount+will+be+credited+to+your+account+within+3+to+15+days."; - whatsappMsgServiceImpl.sendMsg(settlementrefundwhatsupmsg); - whatsappMsgServiceImpl.sendSMS(settlementrefundurlString); - return true; - }else { - return false; - } - } else if (bookingStatus == BookingStatus.REJECTED || bookingStatus == BookingStatus.GCC_BLOCKED && !(refunStatus==RefundStatus.COMPLETED) && !(refunStatus==RefundStatus.CLOSED)) { - applicationLogService.saveLog(bookingDetails.getBookingId(), ApplicationLogs.logsOfMsg.GCC_BLOCKED_DATE.toString(), "Refund will happen shortly"); - String refundFullAmount = paymentGatewayService.refundTheAmount(bookingDetails.getBookingId(), bookingDetails.getUsers().getUserId()); - //System.out.println("refundTheDepositAmount === " + refundFullAmount); - if (refundFullAmount.equals("Refunded")) { - Optional book=bookingDetailsRepository.findById(bookingDetails.getBookingId()); - BookingDetails rejectedbookings=book.get(); - rejectedbookings.setRefundStatus(RefundStatus.COMPLETED); - bookingDetailsRepository.save(rejectedbookings); - String rejectedsms="Your refund amount of Rs. "+rejectedbookings.getAmountReceived()+" for Booking ID "+rejectedbookings.getBookingId()+" has been initiated. The amount will be credited to your account within 3 to 15 days. Thanks for using the GCC Community Hall Booking System."; - String rejectedrefundurlString ="https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to="+rejectedbookings.getUsers().getMobileNo()+"&from=GCCCRP&body="+rejectedsms+"&entityid=1401572690000011081&templateid=1407172346804951524"; - String settlementrefundwhatsupmsg="https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to="+bookingDetails.getUsers().getMobileNo()+"&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+refund+of+Rs.+"+bookingDetails.getAmountReceived()+"+for+Booking+ID+"+bookingDetails.getBookingId()+"+has+been+initiated.+%0AThe+amount+will+be+credited+to+your+account+within+3+to+15+days."; - whatsappMsgServiceImpl.sendMsg(settlementrefundwhatsupmsg); - whatsappMsgServiceImpl.sendSMS(rejectedrefundurlString); - return true; - }else { - return false; - } - } else if (bookingStatus == BookingStatus.CANCELED && !(refunStatus==RefundStatus.COMPLETED) && !(refunStatus==RefundStatus.CLOSED)) { - // System.out.println("Booking status is Cancelled. Booking ID: " + bookingDetails.getBookingId()); - applicationLogService.saveLog(bookingDetails.getBookingId(), ApplicationLogs.logsOfMsg.USER_CANCELLED_BOOKING.toString(), "Refund will happen shortly"); - String refundTheDepositAmount = paymentGatewayService.refundTheDepositAmount(bookingDetails.getBookingId(), bookingDetails.getUsers().getUserId(),bookingDetails.getDepositAmount()); - //System.out.println("refundTheDepositAmount === " + refundTheDepositAmount); - if (refundTheDepositAmount.equals("Refunded")) { - Optional book=bookingDetailsRepository.findById(bookingDetails.getBookingId()); - BookingDetails cancelledbookings=book.get(); - cancelledbookings.setRefundStatus(RefundStatus.COMPLETED); - bookingDetailsRepository.save(cancelledbookings); - String cancelledsms="Your refund amount of Rs. "+cancelledbookings.getDepositAmount()+" for Booking ID "+cancelledbookings.getBookingId()+" has been initiated. The amount will be credited to your account within 3 to 15 days. Thanks for using the GCC Community Hall Booking System."; - String cancelledrefundurlString ="https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to="+cancelledbookings.getUsers().getMobileNo()+"&from=GCCCRP&body="+cancelledsms+"&entityid=1401572690000011081&templateid=1407172346804951524"; - String settlementrefundwhatsupmsg="https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to="+bookingDetails.getUsers().getMobileNo()+"&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+refund+of+Rs.+"+bookingDetails.getDepositAmount()+"+for+Booking+ID+"+bookingDetails.getBookingId()+"+has+been+initiated.+%0AThe+amount+will+be+credited+to+your+account+within+3+to+15+days."; - whatsappMsgServiceImpl.sendMsg(settlementrefundwhatsupmsg); - whatsappMsgServiceImpl.sendSMS(cancelledrefundurlString); - return true; - }else { - return false; - } - } else { - return false; - } - } - - @Override - public BookingDetails updateRefundStatus(int bookingId, RefundStatus status) { - Optional booking= bookingDetailsRepository.findById(bookingId); - if(booking.isPresent()){ - String adminname = (String) session.getAttribute("usertype"); - BookingDetails book = booking.get(); - book.setRefundStatus(status); + public String processRefundRequest(int bookingId) { + try { + Optional bookingOptional = bookingDetailsRepository.findById(bookingId); + if (bookingOptional.isPresent()) { + BookingDetails bookingDetails = bookingOptional.get(); + boolean refundSuccess = SettlementAmountRefund(bookingDetails); + if (refundSuccess) { + return "Refund successful for Booking ID: " + bookingId; + } else { + return "Refund failed for Booking ID: " + bookingId; + } + } else { + return "Booking not found for Booking ID: " + bookingId; + } + } catch (Exception e) { + e.printStackTrace(); + return "An error occurred while processing Booking ID: " + bookingId + ": " + e.getMessage(); + } + } + + + public boolean SettlementAmountRefund(BookingDetails bookingDetails) throws Exception { + BookingStatus bookingStatus = bookingDetails.getBookingStatus(); + RefundStatus refunStatus = bookingDetails.getRefundStatus(); + String adminname = (String) session.getAttribute("usertype"); + if (bookingStatus == BookingStatus.APPROVED && !(refunStatus == RefundStatus.COMPLETED) && !(refunStatus == RefundStatus.CLOSED)) { + applicationLogService.saveLog(bookingDetails.getBookingId(), ApplicationLogs.logsOfMsg.SETTLEMENT_COMPLETED.toString(), "Refund will happen shortly"); + String refundThesettlementAmount = paymentGatewayService.refundTheDepositAmount(bookingDetails.getBookingId(), bookingDetails.getUsers().getUserId(), bookingDetails.getSettlement().getRefundedAmount()); + //System.out.println("refundThesettlementAmount === " + refundThesettlementAmount); + if (refundThesettlementAmount.equals("Refunded")) { + Optional book = bookingDetailsRepository.findById(bookingDetails.getBookingId()); + BookingDetails bookings = book.get(); + //bookinghistoty update + BookingHistory bookingHistory = new BookingHistory(); + bookingHistory.setStartDate(bookingDetails.getStartDate()); + bookingHistory.setEndDate(bookingDetails.getEndDate()); + bookingHistory.setComments(bookingDetails.getComments()); + bookingHistory.setBookingDetails(bookingDetails); + bookingHistory.setBookingStatus(bookingDetails.getBookingStatus()); + bookingHistory.setUpdatedBy(adminname); + bookingHistory.setCdate(new Date()); + bookingHistory.setRefundStatus(bookingDetails.getRefundStatus()); + bookingDetails.setComments("Completed the Refund"); + bookingHistoryRepository.save(bookingHistory); + bookings.setBookingStatus(bookingStatus.COMPLETED); + bookings.setRefundStatus(RefundStatus.COMPLETED); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + String formattedDate = LocalDateTime.now().format(formatter); + bookings.setUpdatedDate(formattedDate); + bookings.setApprovedBy(adminname); + bookingDetailsRepository.save(bookings); + String settlementrefundsms = "Your refund amount of Rs. " + bookings.getSettlement().getRefundedAmount() + " for Booking ID " + bookings.getBookingId() + " has been initiated. The amount will be credited to your account within 3 to 15 days. Thanks for using the GCC Community Hall Booking System."; + String settlementrefundurlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + bookings.getUsers().getMobileNo() + "&from=GCCCRP&body=" + settlementrefundsms + "&entityid=1401572690000011081&templateid=1407172346804951524"; + String settlementrefundwhatsupmsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + bookingDetails.getUsers().getMobileNo() + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+refund+of+Rs.+" + bookingDetails.getSettlement().getRefundedAmount() + "+for+Booking+ID+" + bookingDetails.getBookingId() + "+has+been+initiated.+%0AThe+amount+will+be+credited+to+your+account+within+3+to+15+days."; + whatsappMsgServiceImpl.sendMsg(settlementrefundwhatsupmsg); + whatsappMsgServiceImpl.sendSMS(settlementrefundurlString); + return true; + } else { + return false; + } + } else if (bookingStatus == BookingStatus.REJECTED || bookingStatus == BookingStatus.GCC_BLOCKED && !(refunStatus == RefundStatus.COMPLETED) && !(refunStatus == RefundStatus.CLOSED)) { + applicationLogService.saveLog(bookingDetails.getBookingId(), ApplicationLogs.logsOfMsg.GCC_BLOCKED_DATE.toString(), "Refund will happen shortly"); + String refundFullAmount = paymentGatewayService.refundTheAmount(bookingDetails.getBookingId(), bookingDetails.getUsers().getUserId()); + //System.out.println("refundTheDepositAmount === " + refundFullAmount); + if (refundFullAmount.equals("Refunded")) { + Optional book = bookingDetailsRepository.findById(bookingDetails.getBookingId()); + BookingDetails rejectedbookings = book.get(); + rejectedbookings.setRefundStatus(RefundStatus.COMPLETED); + bookingDetailsRepository.save(rejectedbookings); + String rejectedsms = "Your refund amount of Rs. " + rejectedbookings.getAmountReceived() + " for Booking ID " + rejectedbookings.getBookingId() + " has been initiated. The amount will be credited to your account within 3 to 15 days. Thanks for using the GCC Community Hall Booking System."; + String rejectedrefundurlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + rejectedbookings.getUsers().getMobileNo() + "&from=GCCCRP&body=" + rejectedsms + "&entityid=1401572690000011081&templateid=1407172346804951524"; + String settlementrefundwhatsupmsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + bookingDetails.getUsers().getMobileNo() + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+refund+of+Rs.+" + bookingDetails.getAmountReceived() + "+for+Booking+ID+" + bookingDetails.getBookingId() + "+has+been+initiated.+%0AThe+amount+will+be+credited+to+your+account+within+3+to+15+days."; + whatsappMsgServiceImpl.sendMsg(settlementrefundwhatsupmsg); + whatsappMsgServiceImpl.sendSMS(rejectedrefundurlString); + return true; + } else { + return false; + } + } else if (bookingStatus == BookingStatus.CANCELED && !(refunStatus == RefundStatus.COMPLETED) && !(refunStatus == RefundStatus.CLOSED)) { + // System.out.println("Booking status is Cancelled. Booking ID: " + bookingDetails.getBookingId()); + applicationLogService.saveLog(bookingDetails.getBookingId(), ApplicationLogs.logsOfMsg.USER_CANCELLED_BOOKING.toString(), "Refund will happen shortly"); + String refundTheDepositAmount = paymentGatewayService.refundTheDepositAmount(bookingDetails.getBookingId(), bookingDetails.getUsers().getUserId(), bookingDetails.getDepositAmount()); + //System.out.println("refundTheDepositAmount === " + refundTheDepositAmount); + if (refundTheDepositAmount.equals("Refunded")) { + Optional book = bookingDetailsRepository.findById(bookingDetails.getBookingId()); + BookingDetails cancelledbookings = book.get(); + cancelledbookings.setRefundStatus(RefundStatus.COMPLETED); + bookingDetailsRepository.save(cancelledbookings); + String cancelledsms = "Your refund amount of Rs. " + cancelledbookings.getDepositAmount() + " for Booking ID " + cancelledbookings.getBookingId() + " has been initiated. The amount will be credited to your account within 3 to 15 days. Thanks for using the GCC Community Hall Booking System."; + String cancelledrefundurlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + cancelledbookings.getUsers().getMobileNo() + "&from=GCCCRP&body=" + cancelledsms + "&entityid=1401572690000011081&templateid=1407172346804951524"; + String settlementrefundwhatsupmsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + bookingDetails.getUsers().getMobileNo() + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+refund+of+Rs.+" + bookingDetails.getDepositAmount() + "+for+Booking+ID+" + bookingDetails.getBookingId() + "+has+been+initiated.+%0AThe+amount+will+be+credited+to+your+account+within+3+to+15+days."; + whatsappMsgServiceImpl.sendMsg(settlementrefundwhatsupmsg); + whatsappMsgServiceImpl.sendSMS(cancelledrefundurlString); + return true; + } else { + return false; + } + } else { + return false; + } + } + + @Override + public BookingDetails updateRefundStatus(int bookingId, RefundStatus status) { + Optional booking = bookingDetailsRepository.findById(bookingId); + if (booking.isPresent()) { + String adminname = (String) session.getAttribute("usertype"); + BookingDetails book = booking.get(); + book.setRefundStatus(status); // BookingHistory bookingHistory=new BookingHistory(); // bookingHistory.setStartDate(book.getStartDate()); // bookingHistory.setEndDate(book.getEndDate()); @@ -1640,54 +1506,70 @@ public class BookingServiceImpl implements BookingService { // bookingHistory.setUpdatedBy(adminname); // bookingHistory.setCdate(new Date()); // bookingHistory.setRefundStatus(book.getRefundStatus()); - book.setComments("Refund status Updated to:-"+status); + book.setComments("Refund status Updated to:-" + status); // bookingHistoryRepository.save(bookingHistory); - BookingDetails bookings = bookingDetailsRepository.save(book); - return bookings; - } - return null; - } - - //officer reports - @Override - public List getAllBookingDetailsByZone(String fromDate, String toDate,String zone){ - return bookingDetailsRepository.getAllBookingDetailsByZone(fromDate, toDate, zone); - } - - -@Override - public List getAllBookingDetailsByZoneWithStatus(String fromDate, String toDate, String zone,String bookingStatus){ - return bookingDetailsRepository.getAllBookingDetailsByZoneWithStatus(fromDate, toDate, zone, bookingStatus); - } - -@Override - public List getAllPaymentsDetailsByZone (String fromDate, String toDate,String zone){ - return bookingDetailsRepository.getAllPaymentsDetailsByZone(fromDate, toDate, zone); - } -@Override - public List getBookingHallDetailsReportByZone(String fromDate, String toDate,String zone){ - return bookingDetailsRepository.getBookingHallDetailsReportByZone(fromDate, toDate, zone); - } -//R - @Transactional + BookingDetails bookings = bookingDetailsRepository.save(book); + return bookings; + } + return null; + } + + //officer reports + @Override + public List getAllBookingDetailsByZone(String fromDate, String toDate, String zone) { + return bookingDetailsRepository.getAllBookingDetailsByZone(fromDate, toDate, zone); + } + + + @Override + public List getAllBookingDetailsByZoneWithStatus(String fromDate, String toDate, String zone, String bookingStatus) { + return bookingDetailsRepository.getAllBookingDetailsByZoneWithStatus(fromDate, toDate, zone, bookingStatus); + } + + @Override + public List getAllPaymentsDetailsByZone(String fromDate, String toDate, String zone) { + return bookingDetailsRepository.getAllPaymentsDetailsByZone(fromDate, toDate, zone); + } + + @Override + public List getBookingHallDetailsReportByZone(String fromDate, String toDate, String zone) { + return bookingDetailsRepository.getBookingHallDetailsReportByZone(fromDate, toDate, zone); + } + + //R + @Transactional public Optional updateBookingDatesAndCalendar(int bookingId, String startDat, String endDat) { - Optional optionalBookingDetails = bookingDetailsRepository.findById(bookingId); - //TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition()); - if (optionalBookingDetails.isPresent()) { - BookingDetails bookingDetails = optionalBookingDetails.get(); - String starting=bookingDetails.getStartDate(); - int hallId = bookingDetails.getHallDetails().getHallId(); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); - LocalDate startDate = LocalDate.parse(startDat, formatter); - LocalDate endDate = LocalDate.parse(endDat, formatter); - - // Retrieve existing calendar entries where bookingId matches booking_id1 or booking_id2 - List existingCalendars = bookingCalendarRepository.getCancellingdata1(String.valueOf(bookingId)); - - - // Check if the dates exist and update or create new entries accordingly - String slotOccExpMsg="Dates are already occupied. Please select another date."; - int i=0; + Optional optionalBookingDetails = bookingDetailsRepository.findById(bookingId); + //TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition()); + if (optionalBookingDetails.isPresent()) { + BookingDetails bookingDetails = optionalBookingDetails.get(); + String starting = bookingDetails.getStartDate(); + int hallId = bookingDetails.getHallDetails().getHallId(); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + LocalDate startDate = LocalDate.parse(startDat, formatter); + LocalDate endDate = LocalDate.parse(endDat, formatter); + + // Retrieve existing calendar entries where bookingId matches booking_id1 or booking_id2 + List existingCalendars = bookingCalendarRepository.getCancellingdata1(String.valueOf(bookingId)); + + +// Empty the existing date in calendar + for (BookingCalendar calendar : existingCalendars) { + if (calendar.getBookingId_1() != null && calendar.getBookingId_1().equals(String.valueOf(bookingId))) { + calendar.setMorningSlot(false); + calendar.setBookingId_1(null); + } + if (calendar.getBookingId_2() != null && calendar.getBookingId_2().equals(String.valueOf(bookingId))) { + calendar.setEveningSlot(false); + calendar.setBookingId_2(null); + } + bookingCalendarRepository.save(calendar); + } + + + // Check if the dates exist and update or create new entries accordingly + String slotOccExpMsg = "Dates are already occupied. Please select another date."; + int i = 0; for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) { BookingCalendar bookingCalendar = bookingCalendarRepository.findByBdateAndHallId(date, hallId); if (bookingCalendar != null) { @@ -1697,21 +1579,21 @@ public class BookingServiceImpl implements BookingService { (date.equals(endDate) && bookingDetails.getEndingSlot() == 1 && bookingCalendar.isMorningSlot()) || (date.equals(endDate) && bookingDetails.getEndingSlot() == 2 && bookingCalendar.isEveningSlot())) { - // return "Slot occupied"; + // return "Slot occupied"; throw new SlotOccupiedException(slotOccExpMsg); - }else if(bookingCalendar.isMorningSlot() && bookingCalendar.isEveningSlot() ) { - // return "Slot occupied"; + } else if (bookingCalendar.isMorningSlot() && bookingCalendar.isEveningSlot()) { + // return "Slot occupied"; throw new SlotOccupiedException(slotOccExpMsg); - }else if (!date.equals(endDate) && i!=0 && i != Math.round(bookingDetails.getNoOfDays() -1) + } else if (!date.equals(endDate) && i != 0 && i != Math.round(bookingDetails.getNoOfDays() - 1) && (bookingCalendar.isMorningSlot() || bookingCalendar.isEveningSlot())) { //System.out.println("booking slot occupied:- 227 :-"+Math.round(bookingDetails.getNoOfDays()-1) ); - throw new SlotOccupiedException(slotOccExpMsg);} - else if(date.equals(endDate) && bookingDetails.getEndingSlot() == 2 && bookingCalendar.isMorningSlot() - && i!=0 && i == Math.round(bookingDetails.getNoOfDays() -1)){ - // System.out.println("booking slot occupied:- 240 :-"+Math.round(bookingDetails.getNoOfDays()-1) ); - throw new SlotOccupiedException(slotOccExpMsg); + throw new SlotOccupiedException(slotOccExpMsg); + } else if (date.equals(endDate) && bookingDetails.getEndingSlot() == 2 && bookingCalendar.isMorningSlot() + && i != 0 && i == Math.round(bookingDetails.getNoOfDays() - 1)) { + // System.out.println("booking slot occupied:- 240 :-"+Math.round(bookingDetails.getNoOfDays()-1) ); + throw new SlotOccupiedException(slotOccExpMsg); } @@ -1728,36 +1610,35 @@ public class BookingServiceImpl implements BookingService { if (bookingDetails.getStartingSlot() == 1) { bookingCalendar.setMorningSlot(true); bookingCalendar.setBookingId_1(String.valueOf(bookingId)); - bookingCalendar.setIs_booked(bookingCalendar.getIs_booked()+1); - if(!date.equals(endDate)){ + bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1); + if (!date.equals(endDate)) { bookingCalendar.setEveningSlot(true); bookingCalendar.setBookingId_2(String.valueOf(bookingId)); - bookingCalendar.setIs_booked(bookingCalendar.getIs_booked()+1); - } - else if (startDate.equals(endDate) && bookingDetails.getStartingSlot() == 1 && bookingDetails.getEndingSlot()==2) { + bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1); + } else if (startDate.equals(endDate) && bookingDetails.getStartingSlot() == 1 && bookingDetails.getEndingSlot() == 2) { bookingCalendar.setEveningSlot(true); bookingCalendar.setBookingId_2(String.valueOf(bookingId)); - bookingCalendar.setIs_booked(bookingCalendar.getIs_booked()+1); + bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1); } } else { bookingCalendar.setEveningSlot(true); bookingCalendar.setBookingId_2(String.valueOf(bookingId)); - bookingCalendar.setIs_booked(bookingCalendar.getIs_booked()+1); + bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1); } } else if (date.equals(endDate)) { if (bookingDetails.getEndingSlot() == 1) { bookingCalendar.setMorningSlot(true); bookingCalendar.setBookingId_1(String.valueOf(bookingId)); - bookingCalendar.setIs_booked(bookingCalendar.getIs_booked()+1); + bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1); } else { bookingCalendar.setEveningSlot(true); bookingCalendar.setBookingId_2(String.valueOf(bookingId)); - bookingCalendar.setIs_booked(bookingCalendar.getIs_booked()+1); - if(bookingDetails.getEndingSlot()==2){ + bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1); + if (bookingDetails.getEndingSlot() == 2) { bookingCalendar.setMorningSlot(true); bookingCalendar.setBookingId_1(String.valueOf(bookingId)); - bookingCalendar.setIs_booked(bookingCalendar.getIs_booked()+1); + bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1); } } } else { @@ -1766,45 +1647,33 @@ public class BookingServiceImpl implements BookingService { bookingCalendar.setEveningSlot(true); bookingCalendar.setBookingId_1(String.valueOf(bookingId)); bookingCalendar.setBookingId_2(String.valueOf(bookingId)); - bookingCalendar.setIs_booked(bookingCalendar.getIs_booked()+2); + bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 2); } bookingCalendarRepository.save(bookingCalendar); i++; } - //transactionManager.rollback(status); - updateResheduledBookingDetails(bookingId, startDat, endDat); -// Empty the existing date in calendar - for (BookingCalendar calendar : existingCalendars) { - if (calendar.getBookingId_1() != null && calendar.getBookingId_1().equals(String.valueOf(bookingId))) { - calendar.setMorningSlot(false); - calendar.setBookingId_1(null); - } - if (calendar.getBookingId_2() != null && calendar.getBookingId_2().equals(String.valueOf(bookingId))) { - calendar.setEveningSlot(false); - calendar.setBookingId_2(null); - } - bookingCalendarRepository.save(calendar); - } + //transactionManager.rollback(status); + updateResheduledBookingDetails(bookingId, startDat, endDat); - String rescheduledmsg="Your booking ID "+bookingId+" on "+starting+" has been successfully rescheduled to "+startDate+". Thanks for using the GCC Community Hall Booking System."; - String urlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to="+bookingDetails.getUsers().getMobileNo()+"&from=GCCCRP&body="+rescheduledmsg+"&entityid=1401572690000011081&templateid=1407172346565044999"; - String rescheduleMsg ="https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to="+bookingDetails.getUsers().getMobileNo()+"&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+booking+with+ID+"+bookingId+"+on+"+starting+"+has+been+successfully+rescheduled+to+"+startDate+"+.+%0AThank+you+for+using+the+GCC+Community+Hall+Booking+System."; + String rescheduledmsg = "Your booking ID " + bookingId + " on " + starting + " has been successfully rescheduled to " + startDate + ". Thanks for using the GCC Community Hall Booking System."; + String urlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + bookingDetails.getUsers().getMobileNo() + "&from=GCCCRP&body=" + rescheduledmsg + "&entityid=1401572690000011081&templateid=1407172346565044999"; + String rescheduleMsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + bookingDetails.getUsers().getMobileNo() + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+booking+with+ID+" + bookingId + "+on+" + starting + "+has+been+successfully+rescheduled+to+" + startDate + "+.+%0AThank+you+for+using+the+GCC+Community+Hall+Booking+System."; whatsappMsgServiceImpl.sendMsg(rescheduleMsg); whatsappMsgServiceImpl.sendSMS(urlString); return Optional.of("Booking dates updated successfully."); - } - return Optional.of("Booking not found."); - } - - private void updateResheduledBookingDetails(int bookingId, String startDate, String endDate) { - Optional book=bookingDetailsRepository.findById(bookingId); - BookingDetails bookingDetails= book.get(); + } + return Optional.of("Booking not found."); + } + + private void updateResheduledBookingDetails(int bookingId, String startDate, String endDate) { + Optional book = bookingDetailsRepository.findById(bookingId); + BookingDetails bookingDetails = book.get(); bookingDetails.setScheduleCount(bookingDetails.getScheduleCount() + 1); - //Updating Bookinghistory startDate and End Date - BookingHistory bookingHistory=new BookingHistory(); + //Updating Bookinghistory startDate and End Date + BookingHistory bookingHistory = new BookingHistory(); bookingHistory.setStartDate(bookingDetails.getStartDate()); - bookingHistory.setEndDate(bookingDetails.getEndDate()); + bookingHistory.setEndDate(bookingDetails.getEndDate()); bookingHistory.setComments(bookingDetails.getComments()); bookingHistory.setBookingDetails(bookingDetails); bookingHistory.setBookingStatus(BookingStatus.APPROVED); @@ -1816,588 +1685,607 @@ public class BookingServiceImpl implements BookingService { bookingDetails.setComments("slots Resheduled the Dates"); bookingDetailsRepository.save(bookingDetails); bookingHistoryRepository.save(bookingHistory); -} + } + + @Override + public List getBookingHallDetailsReportByZone1(String fromDate, String toDate, String zone, Integer hallId) { + // TODO Auto-generated method stub + return bookingDetailsRepository.getBookingHallDetailsReportByZone1(fromDate, toDate, zone, hallId); + } + + public List getGccBlockingEvents(String hallId) { + HallDetails hallDetails = hallDetailsRepository.findById(Integer.parseInt(hallId)) + .orElseThrow(() -> new RuntimeException("Hall not found")); + + // Fetch BookingDetails with GCC_BLOCKED status + List bookingDetails = bookingDetailsRepository.findByHallDetailsAndBookingStatus(hallDetails, BookingDetails.BookingStatus.GCC_BLOCKED); + + // Fetch GccBlockingDate with BLOCKED status + List gccBlockingDates = gccBlockingDateRepository.findAllByHallIdAndBlockedStatus(hallId, GccBlockingDate.BlockedStatus.BLOCKED); + + // Combine results into a list of Object (can be more specific if needed) + List results = new ArrayList<>(); + results.addAll(bookingDetails); + results.addAll(gccBlockingDates); + + return results; + } + + @Override + public int getBlockedHallCount(String blockingReason, Date startDate, Date endDate) { + return gccBlockingDateRepository.countBlockedHallsInDateRange(blockingReason, startDate, endDate); + } + + public boolean isBlockingRecordExists(String fromDate, String toDate, List hallIdsList) { + LocalDate fromdate = LocalDate.parse(fromDate); + LocalDate todate = LocalDate.parse(toDate); + List existingRecords = gccBlockingDateRepository.findByFromDateAndToDateBetweenAndHallIdIn(fromdate, todate, hallIdsList); + return !existingRecords.isEmpty(); + } + + @Override + public void cancelAllBookings(String fromDate, String toDate, List hallIdsList, + String reasonforblocking, List selectedBookings, String updatedBy, String[] descriptions, MultipartFile[] documents) { + if (selectedBookings != null && !selectedBookings.isEmpty()) { + for (String bookingIdStr : selectedBookings) { + Integer bookingId = Integer.parseInt(bookingIdStr); + Optional optionalBooking = bookingDetailsRepository.findById(bookingId); + + if (optionalBooking.isPresent()) { + BookingDetails booking = optionalBooking.get(); + BookingStatus currentStatus = booking.getBookingStatus(); + + if (currentStatus == BookingStatus.APPROVED || currentStatus == BookingStatus.WAITING_FOR_NOC || + currentStatus == BookingStatus.WAITING_FOR_NOC_APPROVAL) { + booking.setBookingStatus(BookingStatus.GCC_BLOCKED); + List calendardata = getCancellingdata1(bookingId.toString()); + for (BookingCalendar bb : calendardata) { + if (bookingId != 0 && bb.getBookingId_1() != null && + bookingId.equals(Integer.valueOf(bb.getBookingId_1()))) { + bb.setBookingId_1(null); + bb.setMorningSlot(false); + } + if (bookingId != 0 && bb.getBookingId_2() != null && + bookingId.equals(Integer.valueOf(bb.getBookingId_2()))) { + bb.setBookingId_2(null); + bb.setEveningSlot(false); + } + //bb.setIs_blocked(true); + updateBookingStatus(bb); + } - @Override - public List getBookingHallDetailsReportByZone1(String fromDate, String toDate, String zone,Integer hallId) { - // TODO Auto-generated method stub - return bookingDetailsRepository.getBookingHallDetailsReportByZone1(fromDate, toDate, zone, hallId); - } - - public List getGccBlockingEvents(String hallId) { - HallDetails hallDetails = hallDetailsRepository.findById(Integer.parseInt(hallId)) - .orElseThrow(() -> new RuntimeException("Hall not found")); - - // Fetch BookingDetails with GCC_BLOCKED status - List bookingDetails = bookingDetailsRepository.findByHallDetailsAndBookingStatus(hallDetails, BookingStatus.GCC_BLOCKED); - - // Fetch GccBlockingDate with BLOCKED status - List gccBlockingDates = gccBlockingDateRepository.findAllByHallIdAndBlockedStatus(hallId, GccBlockingDate.BlockedStatus.BLOCKED); - - // Combine results into a list of Object (can be more specific if needed) - List results = new ArrayList<>(); - results.addAll(bookingDetails); - results.addAll(gccBlockingDates); - - return results; - } - - @Override - public int getBlockedHallCount(String blockingReason, Date startDate, Date endDate) { - return gccBlockingDateRepository.countBlockedHallsInDateRange( blockingReason,startDate,endDate); - } - public boolean isBlockingRecordExists(String fromDate, String toDate, List hallIdsList) { - LocalDate fromdate = LocalDate.parse(fromDate); - LocalDate todate = LocalDate.parse(toDate); - List existingRecords = gccBlockingDateRepository.findByFromDateAndToDateBetweenAndHallIdIn(fromdate, todate, hallIdsList); - return !existingRecords.isEmpty(); - } - - @Override - public void cancelAllBookings(String fromDate, String toDate, List hallIdsList, - String reasonforblocking, List selectedBookings, String updatedBy,String[] descriptions,MultipartFile[] documents) { - if (selectedBookings != null && !selectedBookings.isEmpty()) { - for (String bookingIdStr : selectedBookings) { - Integer bookingId = Integer.parseInt(bookingIdStr); - Optional optionalBooking = bookingDetailsRepository.findById(bookingId); - - if (optionalBooking.isPresent()) { - BookingDetails booking = optionalBooking.get(); - BookingStatus currentStatus = booking.getBookingStatus(); - - if (currentStatus == BookingStatus.APPROVED) { - booking.setBookingStatus(BookingStatus.GCC_BLOCKED); - List calendardata =getCancellingdata1(bookingId.toString()); - for (BookingCalendar bb : calendardata) { - bb.setBookingId_1(null); - bb.setBookingId_2(null); - bb.setMorningSlot(false); - bb.setEveningSlot(false); - 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) { - BookingCalendar data =getbyDates(aa, hallId.toString()); - int userbookingbookingId = bookingIds.get(hallIdsList.indexOf(hallId)); - if (data != null) { - data.setBookingId_1(String.valueOf(userbookingbookingId)); - data.setBookingId_2(String.valueOf(userbookingbookingId)); - data.setMorningSlot(true); - data.setEveningSlot(true); - data.setIs_blocked(true); - updateBookingStatus(data); - } else { - 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_blocked(true); - book.setIs_delete(false); - updateBookingStatus(book); - } - } - } - } - updateBookingStatusById(booking.getBookingId(),booking.getBookingStatus().GCC_BLOCKED, reasonforblocking); - //whatsup msg and SMS - String gccblockedsms="Your booking ID "+bookingId+" on "+booking.getStartDate()+" has been blocked by GCC due to "+reasonforblocking+". The entire amount paid will be refunded to your account with in 3 to 15 days."; - String gccblockedurlString ="https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to="+booking.getUsers().getMobileNo()+"&from=GCCCRP&body="+gccblockedsms+"&entityid=1401572690000011081&templateid=1407172346521513227"; - //String gccblockedwhatsupmsg="https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to="+booking.getUsers().getMobileNo()+"&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+booking+with+ID+"+booking.getBookingId()+"+on+"+booking.getBookingDate()+"+has+been+blocked+by+GCC+due+to+"+reasonforblocking+".+%0AThanks+for+using+GCC+Community+Hall+Booking+System."; - String gccblockedwhatsupmsg="https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to="+booking.getUsers().getMobileNo()+"&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+booking+with+ID+"+booking.getBookingId()+"+on+"+booking.getBookingDate()+"+has+been+blocked+by+the+GCC+due+to+Goverment+event++.+%0AThe+entire+amount+paid+will+be+refunded+to+your+account+within+3+to+15+days."; - whatsappMsgServiceImpl.sendMsg(gccblockedwhatsupmsg); - whatsappMsgServiceImpl.sendSMS(gccblockedurlString); - bookingDetailsRepository.save(booking); - } - } - } - } else { - // Create and save a new GCC blocking date 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); - 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); - String bookingIdsString = bookingIds.stream() - .map(String::valueOf) - .collect(Collectors.joining(",")); - gccblockinghistory.setBookingIds(bookingIdsString); - blockingHistoryRepository.save(gccblockinghistory); - if (documents != null && documents.length > 0) { - if (descriptions != null && descriptions.length == documents.length) { - int i = 0; - for (MultipartFile document : documents) { - String filePath = uploadDirectory + "/" + gcc.getBlockingId() + "_" + i + "_" + document.getOriginalFilename(); - String documentUrl = serverPath + "gccblockingdocs/" + gcc.getBlockingId() + "_" + i + "_" + document.getOriginalFilename(); - - 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++; - } - } else { - // Handle case where descriptions array length does not match documents length - } - } - // Iterate through hall IDs and corresponding dates to update BookingCalendar - for (Long hallId : hallIdsList) { - LocalDate fDate = LocalDate.parse(fromDate); - LocalDate tDate = LocalDate.parse(toDate); - List dates = getDateRange(fDate, tDate); - - for (LocalDate date : dates) { - BookingCalendar data =getbyDates(date, hallId.toString()); - int userbookingbookingId = bookingIds.get(hallIdsList.indexOf(hallId)); - if (data != null) { - data.setBookingId_1(String.valueOf(userbookingbookingId)); - data.setBookingId_2(String.valueOf(userbookingbookingId)); - data.setMorningSlot(true); - data.setEveningSlot(true); - data.setIs_blocked(true); - updateBookingStatus(data); - } else { - BookingCalendar book = new BookingCalendar(); - book.setBdate(date); - 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_blocked(true); - book.setIs_delete(false); - updateBookingStatus(book); - } - } - } - } - } - - // Helper methods for date conversion and range calculation - public Date convertStringToDate(String dateString){ - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); - try { - return dateFormat.parse(dateString); - } catch (ParseException e) { - e.printStackTrace(); - return null; - } - } - - public static List getDateRange(LocalDate fDate, LocalDate tDate) { - List dateRange = new ArrayList<>(); - LocalDate currentDate = fDate; - while (!currentDate.isAfter(tDate)) { - dateRange.add(currentDate); - currentDate = currentDate.plusDays(1); - } - return dateRange; - } - - @Override - public List findBookingDetailsByBookingId(Long bookingId) { - return bookingDetailsRepository.findBookingDetailsByBookingId(bookingId); - } - - //admin dashboard - @Override - public Map> getBookingStatistics(LocalDate fromDate, LocalDate toDate, String zone, String division,Integer hallid, String userType) { - List> rawStatistics = bookingDetailsRepository.getBookingStatistics(fromDate, toDate, zone, division, hallid,userType); - return transformData(rawStatistics); - } - - private Map> transformData(List> rawStatistics) { - Map> transformedData = new HashMap<>(); - - for (Map entry : rawStatistics) { - if (entry.isEmpty()) continue; // Skip empty entries - - String category = (String) entry.get("category"); - 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); - - if (category.equals("main")) { - Integer mainTotalAmount = entry.get("main_total_amount") != null ? ((Number) entry.get("main_total_amount")).intValue() : 0; - Integer mainRefundedAmount = entry.get("main_refunded_amount") != null ? ((Number) entry.get("main_refunded_amount")).intValue() : 0; - Integer mainNetAmount = entry.get("main_net_amount") != null ? ((Number) entry.get("main_net_amount")).intValue() : 0; - Integer mainGstAmount = entry.get("main_gst_amount") != null ? ((Number) entry.get("main_gst_amount")).intValue() : 0; - transformedData.get(category).put("main_total_amount", mainTotalAmount); - transformedData.get(category).put("main_net_amount", mainNetAmount); - transformedData.get(category).put("main_refunded_amount", mainRefundedAmount); - transformedData.get(category).put("main_gst_amount", mainGstAmount); - } - if (category.equals("past_future")) { - Integer pastbooking = entry.get("PAST_Events") != null ? ((Number) entry.get("PAST_Events")).intValue() : 0; - Integer futurebooking = entry.get("FUTURE_Events") != null ? ((Number) entry.get("FUTURE_Events")).intValue() : 0; - transformedData.get(category).put("PAST_Events", pastbooking); - transformedData.get(category).put("FUTURE_Events", futurebooking); - } - } - - return transformedData; - } - - public List> getBookingDetailsByHallId(int hallId) { - return bookingDetailsRepository.getBookingDetailsByHallId(hallId); - } - //officer Dashboard - - @Override - public Map> getOfficerDashboard(LocalDate fromDate, LocalDate toDate, String zone, String division,Integer hallid, String userType) { - List> rawStatistics = bookingDetailsRepository.getOfficerDashboard(fromDate, toDate, zone, division, hallid,userType); - return transformedData(rawStatistics); - } - - private Map> transformedData(List> rawStatistics) { - Map> transformedData = new HashMap<>(); - - for (Map entry : rawStatistics) { - if (entry.isEmpty()) continue; // Skip empty entries - - String category = (String) entry.get("category"); - 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); - - if (category.equals("main")) { - Integer mainTotalAmount = entry.get("main_total_amount") != null ? ((Number) entry.get("main_total_amount")).intValue() : 0; - Integer mainNetAmount = entry.get("main_net_amount") != null ? ((Number) entry.get("main_net_amount")).intValue() : 0; - Integer mainRefundedAmount = entry.get("main_refunded_amount") != null ? ((Number) entry.get("main_refunded_amount")).intValue() : 0; - transformedData.get(category).put("main_total_amount", mainTotalAmount); - transformedData.get(category).put("main_net_amount", mainNetAmount); - transformedData.get(category).put("main_refunded_amount", mainRefundedAmount); - } - if (category.equals("past_future")) { - Integer pastbooking = entry.get("PAST_Events") != null ? ((Number) entry.get("PAST_Events")).intValue() : 0; - Integer futurebooking = entry.get("FUTURE_Events") != null ? ((Number) entry.get("FUTURE_Events")).intValue() : 0; - transformedData.get(category).put("PAST_Events", pastbooking); - transformedData.get(category).put("FUTURE_Events", futurebooking); - } - } - - return transformedData; - } - - @Override - public List> getHallDetailsForOfficer(Integer hallIid) { - // TODO Auto-generated method stub - return bookingDetailsRepository.getHallDetailsForOfficer(hallIid); - } - -// @Override + // 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) { + BookingCalendar data = getbyDates(aa, hallId.toString()); + int userbookingbookingId = bookingIds.get(hallIdsList.indexOf(hallId)); + if (data != null) { + data.setBookingId_1(String.valueOf(userbookingbookingId)); + data.setBookingId_2(String.valueOf(userbookingbookingId)); + data.setMorningSlot(true); + data.setEveningSlot(true); + data.setIs_blocked(true); + updateBookingStatus(data); + } else { + 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); + updateBookingStatus(book); + } + } + } + + updateBookingStatusById(booking.getBookingId(), booking.getBookingStatus().GCC_BLOCKED, reasonforblocking); + //whatsup msg and SMS + String gccblockedsms = "Your booking ID " + bookingId + " on " + booking.getStartDate() + " has been blocked by GCC due to " + reasonforblocking + ". The entire amount paid will be refunded to your account with in 3 to 15 days."; + String gccblockedurlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + booking.getUsers().getMobileNo() + "&from=GCCCRP&body=" + gccblockedsms + "&entityid=1401572690000011081&templateid=1407172346521513227"; + //String gccblockedwhatsupmsg="https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to="+booking.getUsers().getMobileNo()+"&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+booking+with+ID+"+booking.getBookingId()+"+on+"+booking.getBookingDate()+"+has+been+blocked+by+GCC+due+to+"+reasonforblocking+".+%0AThanks+for+using+GCC+Community+Hall+Booking+System."; + String gccblockedwhatsupmsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + booking.getUsers().getMobileNo() + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+booking+with+ID+" + booking.getBookingId() + "+on+" + booking.getStartDate() + "+has+been+blocked+by+the+GCC+due+to+Goverment+event++.+%0AThe+entire+amount+paid+will+be+refunded+to+your+account+within+3+to+15+days."; + whatsappMsgServiceImpl.sendMsg(gccblockedwhatsupmsg); + whatsappMsgServiceImpl.sendSMS(gccblockedurlString); + bookingDetailsRepository.save(booking); + } + } + } + } else { + // Create and save a new GCC blocking date 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); + 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); + String bookingIdsString = bookingIds.stream() + .map(String::valueOf) + .collect(Collectors.joining(",")); + gccblockinghistory.setBookingIds(bookingIdsString); + blockingHistoryRepository.save(gccblockinghistory); + if (documents != null && documents.length > 0) { + if (descriptions != null && descriptions.length == documents.length) { + int i = 0; + for (MultipartFile document : documents) { + String filePath = uploadDirectory + "/" + gcc.getBlockingId() + "_" + i + "_" + document.getOriginalFilename(); + String documentUrl = serverPath + "gccblockingdocs/" + gcc.getBlockingId() + "_" + i + "_" + document.getOriginalFilename(); + + 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++; + } + } else { + // Handle case where descriptions array length does not match documents length + } + } + // Iterate through hall IDs and corresponding dates to update BookingCalendar + for (Long hallId : hallIdsList) { + LocalDate fDate = LocalDate.parse(fromDate); + LocalDate tDate = LocalDate.parse(toDate); + List dates = getDateRange(fDate, tDate); + + for (LocalDate date : dates) { + BookingCalendar data = getbyDates(date, hallId.toString()); + int userbookingbookingId = bookingIds.get(hallIdsList.indexOf(hallId)); + if (data != null) { + data.setBookingId_1(String.valueOf(userbookingbookingId)); + data.setBookingId_2(String.valueOf(userbookingbookingId)); + data.setMorningSlot(true); + data.setEveningSlot(true); + data.setIs_blocked(true); + updateBookingStatus(data); + } else { + BookingCalendar book = new BookingCalendar(); + book.setBdate(date); + 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); + updateBookingStatus(book); + } + } + } + } + } + + // Helper methods for date conversion and range calculation + public Date convertStringToDate(String dateString) { + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); + try { + return dateFormat.parse(dateString); + } catch (ParseException e) { + e.printStackTrace(); + return null; + } + } + + public static List getDateRange(LocalDate fDate, LocalDate tDate) { + List dateRange = new ArrayList<>(); + LocalDate currentDate = fDate; + while (!currentDate.isAfter(tDate)) { + dateRange.add(currentDate); + currentDate = currentDate.plusDays(1); + } + return dateRange; + } + + @Override + public List findBookingDetailsByBookingId(Long bookingId) { + return bookingDetailsRepository.findBookingDetailsByBookingId(bookingId); + } + + //admin dashboard + @Override + public Map> getBookingStatistics(LocalDate fromDate, LocalDate toDate, String zone, String division, Integer hallid, String userType) { + List> rawStatistics = bookingDetailsRepository.getBookingStatistics(fromDate, toDate, zone, division, hallid, userType); + return transformData(rawStatistics); + } + + private Map> transformData(List> rawStatistics) { + Map> transformedData = new HashMap<>(); + + for (Map entry : rawStatistics) { + if (entry.isEmpty()) continue; // Skip empty entries + + String category = (String) entry.get("category"); + 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); + + if (category.equals("main")) { + Integer mainTotalAmount = entry.get("main_total_amount") != null ? ((Number) entry.get("main_total_amount")).intValue() : 0; + Integer mainRefundedAmount = entry.get("main_refunded_amount") != null ? ((Number) entry.get("main_refunded_amount")).intValue() : 0; + Integer mainNetAmount = entry.get("main_net_amount") != null ? ((Number) entry.get("main_net_amount")).intValue() : 0; + Integer mainGstAmount = entry.get("main_gst_amount") != null ? ((Number) entry.get("main_gst_amount")).intValue() : 0; + transformedData.get(category).put("main_total_amount", mainTotalAmount); + transformedData.get(category).put("main_net_amount", mainNetAmount); + transformedData.get(category).put("main_refunded_amount", mainRefundedAmount); + transformedData.get(category).put("main_gst_amount", mainGstAmount); + } + if (category.equals("past_future")) { + Integer pastbooking = entry.get("PAST_Events") != null ? ((Number) entry.get("PAST_Events")).intValue() : 0; + Integer futurebooking = entry.get("FUTURE_Events") != null ? ((Number) entry.get("FUTURE_Events")).intValue() : 0; + transformedData.get(category).put("PAST_Events", pastbooking); + transformedData.get(category).put("FUTURE_Events", futurebooking); + } + } + + return transformedData; + } + + public List> getBookingDetailsByHallId(int hallId) { + return bookingDetailsRepository.getBookingDetailsByHallId(hallId); + } + //officer Dashboard + + @Override + public Map> getOfficerDashboard(LocalDate fromDate, LocalDate toDate, String zone, String division, Integer hallid, String userType) { + List> rawStatistics = bookingDetailsRepository.getOfficerDashboard(fromDate, toDate, zone, division, hallid, userType); + return transformedData(rawStatistics); + } + + private Map> transformedData(List> rawStatistics) { + Map> transformedData = new HashMap<>(); + + for (Map entry : rawStatistics) { + if (entry.isEmpty()) continue; // Skip empty entries + + String category = (String) entry.get("category"); + 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); + + if (category.equals("main")) { + Integer mainTotalAmount = entry.get("main_total_amount") != null ? ((Number) entry.get("main_total_amount")).intValue() : 0; + Integer mainNetAmount = entry.get("main_net_amount") != null ? ((Number) entry.get("main_net_amount")).intValue() : 0; + Integer mainRefundedAmount = entry.get("main_refunded_amount") != null ? ((Number) entry.get("main_refunded_amount")).intValue() : 0; + transformedData.get(category).put("main_total_amount", mainTotalAmount); + transformedData.get(category).put("main_net_amount", mainNetAmount); + transformedData.get(category).put("main_refunded_amount", mainRefundedAmount); + } + if (category.equals("past_future")) { + Integer pastbooking = entry.get("PAST_Events") != null ? ((Number) entry.get("PAST_Events")).intValue() : 0; + Integer futurebooking = entry.get("FUTURE_Events") != null ? ((Number) entry.get("FUTURE_Events")).intValue() : 0; + transformedData.get(category).put("PAST_Events", pastbooking); + transformedData.get(category).put("FUTURE_Events", futurebooking); + } + } + + return transformedData; + } + + @Override + public List> getHallDetailsForOfficer(Integer hallIid) { + // TODO Auto-generated method stub + return bookingDetailsRepository.getHallDetailsForOfficer(hallIid); + } + + // @Override // public List getAllPaymentsDetails(String fromDate, String toDate, String paymentStatus) { // // TODO Auto-generated method stub // return bookingDetailsRepository.getAllPaymentsDetails(fromDate, toDate,paymentStatus); // } // - //admin reports - @Override - public List getBookingDetailsByBookingDate(String fromDate, String toDate,String zone,String division,Integer hallid) { - // TODO Auto-generated method stub - - return bookingDetailsRepository.getBookingDetailsByBookingDate(fromDate, toDate,zone, division, hallid); - } - - @Override - public List getBookingDetailsByEventDate(String fromDate, String toDate,String zone,String division,Integer hallid) { - // TODO Auto-generated method stub - return bookingDetailsRepository.getBookingDetailsByEventDate(fromDate, toDate,zone,division, hallid); - } - - @Override - public List getBookingDetailsByBookingDateWithStatus(String fromDate, String toDate, - String bookingStatus,String zone,String division,Integer hallid) { - // TODO Auto-generated method stub - return bookingDetailsRepository.getBookingDetailsByBookingDateWithStatus(fromDate, toDate, bookingStatus,zone, division, hallid); - } - - @Override - public List getBookingDetailsByEventDateWithStatus(String fromDate, String toDate, - String bookingStatus,String zone,String division,Integer hallid) { - // TODO Auto-generated method stub - return bookingDetailsRepository.getBookingDetailsByEventDateWithStatus(fromDate, toDate, bookingStatus,zone, division, hallid); - } - @Override - public List getAllPaymentsDetails(String fromDate, String toDate,String paymentStatus, String zone, String division,Integer hallid) { - // TODO Auto-generated method stub - return bookingDetailsRepository.getAllPaymentsDetails(fromDate, toDate,paymentStatus, zone, division, hallid); - } - - @Override - public List getAllExtraPaymentsDetails(String fromDate, String toDate,String paymentStatus, String zone, String division,Integer hallid) { - // TODO Auto-generated method stub - return bookingDetailsRepository.getAllExtraPaymentsDetails(fromDate, toDate,paymentStatus, zone, division, hallid); - } - - @Override - public List getBookingHallDetailsReportByBookingDate(String fromDate, String toDate,String zone,String division,Integer hallid) { - // TODO Auto-generated method stub - return bookingDetailsRepository.getBookingHallDetailsReportByBookingDate(fromDate, toDate, zone,division, hallid); - } - - @Override - public List getBookingHallDetailsReportByEventDate(String fromDate, String toDate,String zone,String division,Integer hallid) { - // TODO Auto-generated method stub - return bookingDetailsRepository.getBookingHallDetailsReportByEventDate(fromDate, toDate, zone, division, hallid); - } - - @Override - public List getAllBookingsettlementDetailsByBookingDate(String fromDate, String toDate) { - // TODO Auto-generated method stub - return bookingDetailsRepository.getAllBookingsettlementDetailsByBookingDate(fromDate, toDate); - } - - @Override - public List getAllBookingsettlementDetailsByBookingDateWithStatus(String fromDate, - String toDate, String refundStatus) { - // TODO Auto-generated method stub - return bookingDetailsRepository.getAllBookingsettlementDetailsByBookingDateWithStatus(fromDate, toDate, refundStatus); - } - - @Override - public List getAllBookingsettlementDetailsByEventDate(String fromDate, String toDate) { - // TODO Auto-generated method stub - return bookingDetailsRepository.getAllBookingsettlementDetailsByEventDate(fromDate, toDate); - } - - @Override - public List getAllBookingsettlementDetailsByEventDateWithStatus(String fromDate, - String toDate, String refundStatus) { - // TODO Auto-generated method stub - return bookingDetailsRepository.getAllBookingsettlementDetailsByEventDateWithStatus(fromDate, toDate, refundStatus); - } - - @Override - public List getAllBookingDetailsBookingDateByZone(String fromDate, String toDate, - String zone) { - // TODO Auto-generated method stub - return bookingDetailsRepository.getAllBookingDetailsBookingDateByZone(fromDate, toDate, zone); - } - - @Override - public List getAllBookingDetailsEventDateByZone(String fromDate, String toDate, - String zone) { - // TODO Auto-generated method stub - return bookingDetailsRepository.getAllBookingDetailsEventDateByZone(fromDate, toDate, zone); - } - - @Override - public List getAllBookingDetailsBookingDateByZoneWithStatus(String fromDate, String toDate, - String zone, String bookingStatus) { - // TODO Auto-generated method stub - return bookingDetailsRepository.getAllBookingDetailsBookingDateByZoneWithStatus(fromDate, toDate, zone, bookingStatus); - } - - @Override - public List getAllBookingDetailsEventDateByZoneWithStatus(String fromDate, String toDate, - String zone, String bookingStatus) { - // TODO Auto-generated method stub - return bookingDetailsRepository.getAllBookingDetailsEventDateByZoneWithStatus(fromDate, toDate, zone, bookingStatus); - } - - @Override - public List getAllBookingsettlementDetailsByZoneByBookingDate(String fromDate, - String toDate, String zone) { - // TODO Auto-generated method stub - return bookingDetailsRepository.getAllBookingsettlementDetailsByZoneByBookingDate(fromDate, toDate, zone); - } - - @Override - public List getAllBookingsettlementDetailsByZoneByEventDate(String fromDate, String toDate, - String zone) { - // TODO Auto-generated method stub - return bookingDetailsRepository.getAllBookingsettlementDetailsByZoneByEventDate(fromDate, toDate, zone); - } - - @Override - public List getAllBookingsettlementDetailsByZoneByBookingDateWithStatus(String fromDate, - String toDate, String zone, String refundStatus) { - // TODO Auto-generated method stub - return bookingDetailsRepository.getAllBookingsettlementDetailsByZoneByBookingDateWithStatus(fromDate, toDate, zone, refundStatus); - - } - - @Override - public List getAllBookingsettlementDetailsByZoneByEventDateWithStatus(String fromDate, - String toDate, String zone, String refundStatus) { - // TODO Auto-generated method stub - return bookingDetailsRepository.getAllBookingsettlementDetailsByZoneByEventDateWithStatus(fromDate, toDate, zone, refundStatus); - } - - @Override - public List getBookingHallDetailsReportByZoneByBookingDate(String fromDate, String toDate, - String zone) { - // TODO Auto-generated method stub - return bookingDetailsRepository.getBookingHallDetailsReportByZoneByBookingDate(fromDate, toDate, zone); - } - - @Override - public List getBookingHallDetailsReportByZoneByEventDate(String fromDate, String toDate, - String zone) { - // TODO Auto-generated method stub - return bookingDetailsRepository.getBookingHallDetailsReportByZoneByEventDate(fromDate, toDate, zone); - } - - @Override - public List getBookingHallDetailsReportByZoneByBookingDateHallname(String fromDate, String toDate, - String zone, Integer hallId) { - // TODO Auto-generated method stub - return bookingDetailsRepository.getBookingHallDetailsReportByZoneByBookingDateHallname(fromDate, toDate, zone, hallId); - } - - @Override - public List getBookingHallDetailsReportByZoneByEventDateHallname(String fromDate, String toDate, - String zone, Integer hallId) { - // TODO Auto-generated method stub - return bookingDetailsRepository.getBookingHallDetailsReportByZoneByEventDateHallname(fromDate, toDate, zone, hallId); - } - - //gccapps - @Override - public List getApprovedBookingDetails() { - return bookingDetailsRepository.findByBookingStatus(BookingStatus.APPROVED); - } - - @Override - public List getRejectedBookingDetails() { - return bookingDetailsRepository.findByBookingStatus(BookingStatus.REJECTED); - } - - @Override - public List getWaitingforNOCapproval() { - return bookingDetailsRepository.findByBookingStatus(BookingStatus.WAITING_FOR_NOC_APPROVAL); - } - - @Override - public List getAllPaymentsDetails(String fromDate, String toDate) { - // TODO Auto-generated method stub - //return bookingDetailsRepository.getAllPaymentsDetails(fromDate, toDate); - return null; - } - - @Override - public List getPastsEvents(){ - return bookingDetailsRepository.findPastsEvents(); - } - - - @Override - public List getPresentsEvents(){ - return bookingDetailsRepository.findPresentsEvents(); - } - - - @Override - public List getFuturesEvents(){ - return bookingDetailsRepository.findFuturesEvents(); - } - - @Override - public List getSettlementApprovedList() { - return bookingDetailsRepository.getSettlementApprovedList(); - } - - @Override - public List> getHallDetails(Integer hall_id) { - // TODO Auto-generated method stub - //return bookingDetailsRepository.getHallDetails(hall_id); - return null; - } - - public List getUserDetailsByBookingDate(String fromDate, String toDate) { - return userRepository.findUserDetailsByBookingDate(fromDate, toDate); - } - - //developer - @Override - public List getTransactionresponse(String fromDate, String toDate, Long bookingId, Long hallId){ - return transactionResponseRepository.getTransactionResponseByBookingId(fromDate,toDate,bookingId,hallId); - } + //admin reports + @Override + public List getBookingDetailsByBookingDate(String fromDate, String toDate, String zone, String division, Integer hallid) { + // TODO Auto-generated method stub + + return bookingDetailsRepository.getBookingDetailsByBookingDate(fromDate, toDate, zone, division, hallid); + } + + @Override + public List getBookingDetailsByEventDate(String fromDate, String toDate, String zone, String division, Integer hallid) { + // TODO Auto-generated method stub + return bookingDetailsRepository.getBookingDetailsByEventDate(fromDate, toDate, zone, division, hallid); + } + + @Override + public List getBookingDetailsByBookingDateWithStatus(String fromDate, String toDate, + String bookingStatus, String zone, String division, Integer hallid) { + // TODO Auto-generated method stub + return bookingDetailsRepository.getBookingDetailsByBookingDateWithStatus(fromDate, toDate, bookingStatus, zone, division, hallid); + } + + @Override + public List getBookingDetailsByEventDateWithStatus(String fromDate, String toDate, + String bookingStatus, String zone, String division, Integer hallid) { + // TODO Auto-generated method stub + return bookingDetailsRepository.getBookingDetailsByEventDateWithStatus(fromDate, toDate, bookingStatus, zone, division, hallid); + } + + @Override + public List getAllPaymentsDetails(String fromDate, String toDate, String paymentStatus, String zone, String division, Integer hallid) { + // TODO Auto-generated method stub + return bookingDetailsRepository.getAllPaymentsDetails(fromDate, toDate, paymentStatus, zone, division, hallid); + } + + @Override + public List getAllExtraPaymentsDetails(String fromDate, String toDate, String paymentStatus, String zone, String division, Integer hallid) { + // TODO Auto-generated method stub + return bookingDetailsRepository.getAllExtraPaymentsDetails(fromDate, toDate, paymentStatus, zone, division, hallid); + } + + @Override + public List getBookingHallDetailsReportByBookingDate(String fromDate, String toDate, String zone, String division, Integer hallid) { + // TODO Auto-generated method stub + return bookingDetailsRepository.getBookingHallDetailsReportByBookingDate(fromDate, toDate, zone, division, hallid); + } + + @Override + public List getBookingHallDetailsReportByEventDate(String fromDate, String toDate, String zone, String division, Integer hallid) { + // TODO Auto-generated method stub + return bookingDetailsRepository.getBookingHallDetailsReportByEventDate(fromDate, toDate, zone, division, hallid); + } + + @Override + public List getAllBookingsettlementDetailsByBookingDate(String fromDate, String toDate) { + // TODO Auto-generated method stub + return bookingDetailsRepository.getAllBookingsettlementDetailsByBookingDate(fromDate, toDate); + } + + @Override + public List getAllBookingsettlementDetailsByBookingDateWithStatus(String fromDate, + String toDate, String refundStatus) { + // TODO Auto-generated method stub + return bookingDetailsRepository.getAllBookingsettlementDetailsByBookingDateWithStatus(fromDate, toDate, refundStatus); + } + + @Override + public List getAllBookingsettlementDetailsByEventDate(String fromDate, String toDate) { + // TODO Auto-generated method stub + return bookingDetailsRepository.getAllBookingsettlementDetailsByEventDate(fromDate, toDate); + } + + @Override + public List getAllBookingsettlementDetailsByEventDateWithStatus(String fromDate, + String toDate, String refundStatus) { + // TODO Auto-generated method stub + return bookingDetailsRepository.getAllBookingsettlementDetailsByEventDateWithStatus(fromDate, toDate, refundStatus); + } + + @Override + public List getAllBookingDetailsBookingDateByZone(String fromDate, String toDate, + String zone) { + // TODO Auto-generated method stub + return bookingDetailsRepository.getAllBookingDetailsBookingDateByZone(fromDate, toDate, zone); + } + + @Override + public List getAllBookingDetailsEventDateByZone(String fromDate, String toDate, + String zone) { + // TODO Auto-generated method stub + return bookingDetailsRepository.getAllBookingDetailsEventDateByZone(fromDate, toDate, zone); + } + + @Override + public List getAllBookingDetailsBookingDateByZoneWithStatus(String fromDate, String toDate, + String zone, String bookingStatus) { + // TODO Auto-generated method stub + return bookingDetailsRepository.getAllBookingDetailsBookingDateByZoneWithStatus(fromDate, toDate, zone, bookingStatus); + } + + @Override + public List getAllBookingDetailsEventDateByZoneWithStatus(String fromDate, String toDate, + String zone, String bookingStatus) { + // TODO Auto-generated method stub + return bookingDetailsRepository.getAllBookingDetailsEventDateByZoneWithStatus(fromDate, toDate, zone, bookingStatus); + } + + @Override + public List getAllBookingsettlementDetailsByZoneByBookingDate(String fromDate, + String toDate, String zone) { + // TODO Auto-generated method stub + return bookingDetailsRepository.getAllBookingsettlementDetailsByZoneByBookingDate(fromDate, toDate, zone); + } + + @Override + public List getAllBookingsettlementDetailsByZoneByEventDate(String fromDate, String toDate, + String zone) { + // TODO Auto-generated method stub + return bookingDetailsRepository.getAllBookingsettlementDetailsByZoneByEventDate(fromDate, toDate, zone); + } + + @Override + public List getAllBookingsettlementDetailsByZoneByBookingDateWithStatus(String fromDate, + String toDate, String zone, String refundStatus) { + // TODO Auto-generated method stub + return bookingDetailsRepository.getAllBookingsettlementDetailsByZoneByBookingDateWithStatus(fromDate, toDate, zone, refundStatus); + + } + + @Override + public List getAllBookingsettlementDetailsByZoneByEventDateWithStatus(String fromDate, + String toDate, String zone, String refundStatus) { + // TODO Auto-generated method stub + return bookingDetailsRepository.getAllBookingsettlementDetailsByZoneByEventDateWithStatus(fromDate, toDate, zone, refundStatus); + } + + @Override + public List getBookingHallDetailsReportByZoneByBookingDate(String fromDate, String toDate, + String zone) { + // TODO Auto-generated method stub + return bookingDetailsRepository.getBookingHallDetailsReportByZoneByBookingDate(fromDate, toDate, zone); + } + + @Override + public List getBookingHallDetailsReportByZoneByEventDate(String fromDate, String toDate, + String zone) { + // TODO Auto-generated method stub + return bookingDetailsRepository.getBookingHallDetailsReportByZoneByEventDate(fromDate, toDate, zone); + } + + @Override + public List getBookingHallDetailsReportByZoneByBookingDateHallname(String fromDate, String toDate, + String zone, Integer hallId) { + // TODO Auto-generated method stub + return bookingDetailsRepository.getBookingHallDetailsReportByZoneByBookingDateHallname(fromDate, toDate, zone, hallId); + } + + @Override + public List getBookingHallDetailsReportByZoneByEventDateHallname(String fromDate, String toDate, + String zone, Integer hallId) { + // TODO Auto-generated method stub + return bookingDetailsRepository.getBookingHallDetailsReportByZoneByEventDateHallname(fromDate, toDate, zone, hallId); + } + + //gccapps + @Override + public List getApprovedBookingDetails() { + return bookingDetailsRepository.findByBookingStatus(BookingDetails.BookingStatus.APPROVED); + } + + @Override + public List getRejectedBookingDetails() { + return bookingDetailsRepository.findByBookingStatus(BookingDetails.BookingStatus.REJECTED); + } + + @Override + public List getWaitingforNOCapproval() { + return bookingDetailsRepository.findByBookingStatus(BookingDetails.BookingStatus.WAITING_FOR_NOC_APPROVAL); + } + + @Override + public List getAllPaymentsDetails(String fromDate, String toDate) { + // TODO Auto-generated method stub + //return bookingDetailsRepository.getAllPaymentsDetails(fromDate, toDate); + return null; + } + + @Override + public List getPastsEvents() { + return bookingDetailsRepository.findPastsEvents(); + } + + + @Override + public List getPresentsEvents() { + return bookingDetailsRepository.findPresentsEvents(); + } + + + @Override + public List getFuturesEvents() { + return bookingDetailsRepository.findFuturesEvents(); + } + @Override - public List getRefundResponse(String fromDate, String toDate,Long bookingId){ - return transRefundResRepository.getRefundResponseByBookingId(fromDate,toDate,bookingId); - } + public List getSettlementApprovedList() { + return bookingDetailsRepository.getSettlementApprovedList(); + } + + @Override + public List> getHallDetails(Integer hall_id) { + // TODO Auto-generated method stub + //return bookingDetailsRepository.getHallDetails(hall_id); + return null; + } + + public List getUserDetailsByBookingDate(String fromDate, String toDate) { + return userRepository.findUserDetailsByBookingDate(fromDate, toDate); + } + + //developer + @Override + public List getTransactionresponse(String fromDate, String toDate, Long bookingId, Long hallId) { + return transactionResponseRepository.getTransactionResponseByBookingId(fromDate, toDate, bookingId, hallId); + } + + @Override + public List getRefundResponse(String fromDate, String toDate, Long bookingId) { + return transRefundResRepository.getRefundResponseByBookingId(fromDate, toDate, bookingId); + } + + @Override + public List getBookingCalendarDetails(String fromDate, String toDate, Long bookingId, String hallName) { + return bookingCalendarRepository.findBookingCalendarDetails(fromDate, toDate, bookingId, hallName); + } + @Override - public List getBookingCalendarDetails(String fromDate, String toDate,Long bookingId, String hallName) { - return bookingCalendarRepository.findBookingCalendarDetails(fromDate, toDate, bookingId,hallName); + public List getBookingsByDateAndHall(String bookingDate, Long hallId) { + LocalDate date = LocalDate.parse(bookingDate); // Ensure format matches yyyy-MM-dd + return bookingDetailsRepository.findByBookingDateAndHallId(date, hallId); } diff --git a/src/main/resources/templates/admin/adminpage.html b/src/main/resources/templates/admin/adminpage.html index 7fac9fa3..3ee0970d 100644 --- a/src/main/resources/templates/admin/adminpage.html +++ b/src/main/resources/templates/admin/adminpage.html @@ -130,7 +130,7 @@ + Material diff --git a/src/main/resources/templates/admin/caretakerpage.html b/src/main/resources/templates/admin/caretakerpage.html index 06edcd18..5b0ced38 100644 --- a/src/main/resources/templates/admin/caretakerpage.html +++ b/src/main/resources/templates/admin/caretakerpage.html @@ -314,15 +314,15 @@ let usedUnits = endReading - startReading; // Show total used units document.getElementById("totalUsedUnits").style.display = "block"; - document.getElementById("totalUsedUnits").innerText = usedUnits; - document.getElementById("hiddenTotalUsedUnits").value = usedUnits; + document.getElementById("totalUsedUnits").innerText = usedUnits.toFixed(2); + document.getElementById("hiddenTotalUsedUnits").value = usedUnits.toFixed(2); let totalEBAmount = usedUnits * parseFloat(document.getElementById("ebCostPerUnit").value) || 0; // Show total EB amount document.getElementById("totalEBAmount").style.display = "block"; document.getElementById("totalEBAmount").innerText = totalEBAmount.toFixed(2); - document.getElementById("hiddenTotalEBAmount").value = totalEBAmount; + document.getElementById("hiddenTotalEBAmount").value = totalEBAmount.toFixed(2); calculateSettlementAmount(); } diff --git a/src/main/resources/templates/admin/developer.html b/src/main/resources/templates/admin/developer.html index 7acd2fd3..660a599e 100644 --- a/src/main/resources/templates/admin/developer.html +++ b/src/main/resources/templates/admin/developer.html @@ -55,195 +55,195 @@ - - +
+ + + + + + + + + + + + + + + + + + + + + + + + +
S.NoBooking IdHall IdAmountStatus CodeTransaction IdUser Id
0
- -
- +
+ + + + + + + + + + + + + + + + + + + + + + + + +
S.NoBooking IdBooking DateRefund StatusAmountTransaction IdUser Id
0
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
S.NoBooking DateBooking Id1Booking Id2Morning SlotEvening SlotHall NameHall Id
0
+
-
- + + + +
+ + + +
+ - + + + // Function to reset booking checkboxes + function resetBookingCheckboxes() { + $("#bookingTableBody input[type='checkbox']").prop('checked', false); + } + + // Function to update hall checkboxes based on selected bookings + function updateHallCheckboxes() { + // Get selected bookings' hall IDs + var selectedHallIds = Array.from(document.querySelectorAll('#bookingTableBody input[type="checkbox"]:checked')) + .map(cb => cb.getAttribute('data-additional-value')); + + // Update hall checkboxes + document.querySelectorAll('#hallSelectOptions input[type="checkbox"]').forEach(cb => { + const hallId = cb.value; + + if (selectedHallIds.includes(hallId)) { + cb.style.display = ''; // Show checkboxes for selected hall IDs + cb.checked = true; // Keep hall IDs in selectedHallIds checked + } else { + cb.style.display = ''; // Ensure that the checkbox remains visible + cb.checked = false; // Uncheck hall IDs not in selectedHallIds + } + }); + + updateSelectOptions(selectedHallIds); + } + + function updateSelectOptions(selectedHallIds) { + var selectElement = document.querySelector('#hallSelectLabel select'); + var selectedIdsSet = new Set(selectedHallIds); + + // Remove options that are no longer selected + Array.from(selectElement.options).forEach(option => { + if (!selectedIdsSet.has(option.value)) { + selectElement.remove(option.index); + } + }); + + // Add new options for IDs that are selected but not yet in the dropdown + selectedIdsSet.forEach(id => { + // Check if an option with this ID already exists + if (![...selectElement.options].some(option => option.value === id)) { + var newOption = document.createElement('option'); + newOption.value = id; + newOption.textContent = `${id}`; // Ensure text is set correctly + selectElement.appendChild(newOption); + } + }); + + // Update the text content of the select box to show selected IDs + var selectBoxText = Array.from(selectedIdsSet).map(id => `${id}`).join(', '); + var firstOption = selectElement.options[0]; + if (firstOption) { + firstOption.textContent = selectBoxText || 'Select Halls'; + } else { + // Handle the case where no options are left + var newOption = document.createElement('option'); + newOption.value = ''; + newOption.textContent = selectBoxText || 'Select Halls'; + selectElement.appendChild(newOption); + } + + // Log the current state of options for debugging + //console.log("Current dropdown options:"); + Array.from(selectElement.options).forEach(option => { + //console.log(Value: ${option.value}, Text: ${option.textContent}); + }); + } + + // Ensure this function is called whenever the checkboxes are changed + $(".bookingCheckbox").change(function () { + // Collect selected hall IDs + var selectedHallIds = Array.from(document.querySelectorAll('#hallSelectOptions input[type="checkbox"]:checked')) + .map(cb => cb.value); + + updateSelectOptions(selectedHallIds); + }); + + // Function to update the display of selected hall IDs + function updateHallDisplay() { + var checkedHallIds = Array.from(document.querySelectorAll('#hallSelectOptions input[type="checkbox"]:checked')) + .map(cb => cb.value); + + //console.log("Selected Hall IDs:", checkedHallIds.join(', ')); + + // Optional: Update a UI element with the selected hall IDs + // For example, set the text of a span element: + // $("#selectedHallIdsDisplay").text(checkedHallIds.join(', ')); + } + }); + + function getBlockedevents() { + + var selectedHalls = Array.from(document.querySelectorAll('#hallSelectOptions input[type="checkbox"]:checked')) + .map(cb => cb.value) + .filter(value => !isNaN(value)); // Filter out non-numeric values + + var fromDate = $("#fromDate").val(); + var toDate = $("#toDate").val(); + var reasonforBlocking = $("#reasonforBlocking").val(); + if (!reasonforBlocking) { + Swal.fire( + 'Error!', + 'Reason For Blocking is required.', + 'error' + ); + } + $.ajax({ + url: '/communityhall/admin/api/blockedevents', + type: 'GET', + data: { + hallIds: selectedHalls.join(','), // Pass selected hall IDs as comma-separated values + fromDate: fromDate, + toDate: toDate, + reasonforBlocking: reasonforBlocking, + }, + success: function (response) { + }, + error: function (xhr, status, error) { + console.error(xhr.responseText); // Log the error for debugging + // Handle error + } + }); + } + + function cancelBlockedevent(element) { + var blockingId = element.getAttribute('data-blocking-id'); + var fromDate = element.getAttribute('data-from-date'); + var endDate = element.getAttribute('data-end-date'); + Swal.fire({ + title: 'Are you sure?', + text: 'Do you want to unblock this item?', + icon: 'warning', + showCancelButton: true, + confirmButtonText: 'Yes, unblock it!', + cancelButtonText: 'No, keep it blocked' + }).then((result) => { + if (result.isConfirmed) { + $.ajax({ + url: '/communityhall/admin/api/cancelByid', + type: 'GET', + data: { + blockingId: blockingId, + fromDate: fromDate, + endDate: endDate + }, + success: function (response) { + console.log("Unblock response:", response); + $("#viewdetails").modal('hide'); + window.location.reload(); + }, + error: function (xhr, status, error) { + console.error("Error unblocking:", xhr.responseText); // Log the error for debugging + // Handle error + } + }); + } + }); + } + + function unblockSpecificBlockedevent(blockingId, bookingId, fromDate, hallId) { + Swal.fire({ + title: 'Are you sure?', + text: 'Do you want to unblock this item?', + icon: 'warning', + showCancelButton: true, + confirmButtonText: 'Yes, unblock it!', + cancelButtonText: 'No, keep it blocked' + }).then((result) => { + if (result.isConfirmed) { + $.ajax({ + url: '/communityhall/admin/api/cancelByid', + type: 'GET', + data: { + blockingId: blockingId, + bookingId: bookingId, + fromDate: fromDate, + hallId: hallId + }, + success: function (response) { + $("#viewdetails").modal('hide'); + window.location.reload(); + }, + error: function (xhr, status, error) { + console.error("Error unblocking:", xhr.responseText); // Log the error for debugging + // Handle error + } + }); + } + }); + } + + function formatDate(date) { + var d = new Date(date), + month = '' + (d.getMonth() + 1), + day = '' + d.getDate(), + year = d.getFullYear(); + + if (month.length < 2) month = '0' + month; + if (day.length < 2) day = '0' + day; + + return [year, month, day].join('-'); + } + + + document.addEventListener("DOMContentLoaded", function () { + var today = new Date(); + var yyyy = today.getFullYear(); + var mm = String(today.getMonth() + 1).padStart(2, '0'); + var dd = String(today.getDate()).padStart(2, '0'); + var formattedToday = yyyy + '-' + mm + '-' + dd; + + // Set min attribute to today for both date inputs + document.getElementById("fromDate").setAttribute("min", formattedToday); + document.getElementById("toDate").setAttribute("min", formattedToday); + }); + + // Function to show/hide checkboxes + // Function to show/hide checkboxes + function toggleCheckboxArea(id, onlyHide = false) { + var checkboxes = document.getElementById(id); + var displayValue = checkboxes.style.display; + + if (displayValue !== "block") { + if (onlyHide === false) { + checkboxes.style.display = "block"; + } + } else { + checkboxes.style.display = "none"; + } + } + + // Function to initialize the zones + function getZone() { + $.ajax({ + type: "GET", + url: '/communityhall/user/api/getZone', + success: function (data) { + const uniqueZones = [...new Set(data.map(item => item.zone))]; + const zoneMenu = document.getElementById('zoneSelectOptions'); + zoneMenu.innerHTML = ''; // Clear existing options + + // Add "All Zones" checkbox + const allZonesCheckbox = document.createElement('input'); + allZonesCheckbox.type = 'checkbox'; + allZonesCheckbox.value = 'All Zones'; + allZonesCheckbox.name = 'zone'; + allZonesCheckbox.addEventListener('change', function () { + toggleAllZones(this.checked); + }); + const allZonesLabel = document.createElement('label'); + allZonesLabel.htmlFor = 'allZonesCheckbox'; + allZonesLabel.textContent = 'All Zones'; + allZonesLabel.prepend(allZonesCheckbox); + zoneMenu.appendChild(allZonesLabel); + + uniqueZones.forEach(zone => { + const label = document.createElement('label'); + const checkbox = document.createElement('input'); + checkbox.type = 'checkbox'; + checkbox.value = zone; + checkbox.id = zone; + checkbox.name = 'zone'; + label.htmlFor = zone; + label.textContent = zone; + label.prepend(checkbox); + zoneMenu.appendChild(label); + + // Bind change event + checkbox.addEventListener('change', function () { + loadHallsbyzone(); + checkboxStatusChange('zoneSelectOptions', 'zoneSelectLabel'); + }); + }); + }, + error: function (xhr, status, error) { + console.error('Error loading zones:', error); + } + }); + } + + // Function to toggle all zones checkboxes + function toggleAllZones(checked) { + const zoneCheckboxes = document.querySelectorAll('#zoneSelectOptions input[type="checkbox"]'); + zoneCheckboxes.forEach(checkbox => { + checkbox.checked = checked; + }); + loadHallsbyzone(); + checkboxStatusChange('zoneSelectOptions', 'zoneSelectLabel'); + } + + function addHallCheckbox(hallMenu, hall) { + const label = document.createElement('label'); + const checkbox = document.createElement('input'); + checkbox.type = 'checkbox'; + checkbox.value = hall.hallId; + checkbox.id = hall.hallName; + checkbox.name = 'hall'; + + label.htmlFor = hall.hallId; + + // Remove leading comma if present + const hallName = hall.hallName.trim(); // Remove leading and trailing whitespace + label.textContent = hallName.replace(/^, */, ''); // Remove leading comma and spaces, if any + + label.prepend(checkbox); + + hallMenu.appendChild(label); + + // Bind change event + checkbox.addEventListener('change', function () { + checkboxStatusChange('hallSelectOptions', 'hallSelectLabel'); + }); + } + + // Function to load halls based on selected zones + function loadHallsbyzone() { + const selectedZones = Array.from(document.querySelectorAll('#zoneSelectOptions input[type="checkbox"]:checked')).map(cb => cb.value); + + if (selectedZones.length === 0) { + document.getElementById('hallSelectOptions').innerHTML = ''; + return; + } + + $.ajax({ + url: '/communityhall/user/api/hallsbyzone', + method: 'GET', + data: {zones: selectedZones.join(',')}, // Pass selected zones to the backend + success: function (response) { + const hallMenu = document.getElementById('hallSelectOptions'); + hallMenu.innerHTML = ''; // Clear existing options + + // Add "All Halls" checkbox + const allHallsCheckbox = document.createElement('input'); + allHallsCheckbox.type = 'checkbox'; + allHallsCheckbox.addEventListener('change', function () { + toggleAllHalls(this.checked); + }); + + const allHallsLabel = document.createElement('label'); + allHallsLabel.htmlFor = 'allHallsCheckbox'; + allHallsLabel.textContent = 'All Halls'; + allHallsLabel.prepend(allHallsCheckbox); + hallMenu.appendChild(allHallsLabel); + + // Add individual hall checkboxes + response.forEach(function (hall) { + addHallCheckbox(hallMenu, hall); + }); + }, + error: function (xhr, status, error) { + console.error('Error loading halls:', error); + } + }); + } + + // Function to toggle all halls checkboxes + function toggleAllHalls(checked) { + const hallCheckboxes = document.querySelectorAll('#hallSelectOptions input[type="checkbox"]'); + hallCheckboxes.forEach(checkbox => { + checkbox.checked = checked; + }); + checkboxStatusChange('hallSelectOptions', 'hallSelectLabel'); + } + + function checkboxStatusChange(optionsId, labelId) { + var multiselect = document.getElementById(labelId); + var multiselectOption = multiselect.getElementsByTagName('option')[0]; + + var values = []; + var checkboxes = document.getElementById(optionsId); + var checkedCheckboxes = checkboxes.querySelectorAll('input[type=checkbox]:checked'); + + // Check if all zones are selected + var allZonesCheckbox = document.getElementById('allZonesCheckbox'); + var zoneCheckboxes = document.querySelectorAll('#zoneSelectOptions input[type="checkbox"]'); + var allZonesChecked = Array.from(zoneCheckboxes).every(checkbox => checkbox.checked); + + for (const item of checkedCheckboxes) { + var checkboxValue = item.getAttribute('id'); + if (allZonesChecked && checkboxValue === 'All Zones') { + // Skip the "All Zones" label if all zones are selected + continue; + } + values.push(checkboxValue); + } + + var dropdownValue = "Nothing is selected"; + if (values.length > 0) { + dropdownValue = values.join(', ').replace(/^, */, ''); // Remove leading comma and spaces if any + } + + multiselectOption.innerText = dropdownValue; + } + + + window.onload = function () { + document.addEventListener("click", function (evt) { + var zoneFlyoutElement = document.getElementById('zoneMultiselect'), + hallFlyoutElement = document.getElementById('hallMultiselect'), + targetElement = evt.target; // clicked element + + do { + if (targetElement == zoneFlyoutElement || targetElement == hallFlyoutElement) { + return; // Click inside + } + targetElement = targetElement.parentNode; + } while (targetElement); + + // Click outside + toggleCheckboxArea('zoneSelectOptions', true); + toggleCheckboxArea('hallSelectOptions', true); + }); + }; + + document.addEventListener('DOMContentLoaded', function () { + function clearModalFields() { + // Clear text inputs + document.querySelectorAll('#viewdetails input[type="text"], #viewdetails input[type="date"]').forEach(input => { + input.value = ''; + }); + + // Reset select elements + document.querySelectorAll('#viewdetails select').forEach(select => { + select.selectedIndex = 0; // Reset to default option + }); + + // Uncheck checkboxes and clear their container + document.querySelectorAll('#viewdetails .checkboxes input[type="checkbox"]').forEach(checkbox => { + checkbox.checked = false; + }); + document.querySelectorAll('#viewdetails .checkboxes').forEach(container => { + container.innerHTML = ''; // Clear all checkboxes from the container + }); + + // Add default options for zones and halls + document.querySelector('#zoneMultiselect select').innerHTML = ''; + document.querySelector('#hallMultiselect select').innerHTML = ''; + + // Optionally, hide content area if needed + document.getElementById('bookinglistdataTable').style.display = 'none'; + } + + // Event listener for when the modal is hidden + document.getElementById('viewdetails').addEventListener('hidden.bs.modal', clearModalFields); + }); + + function formatDate(date) { + let d = new Date(date), + month = '' + (d.getMonth() + 1), + day = '' + d.getDate(), + year = d.getFullYear(); + + if (month.length < 2) month = '0' + month; + if (day.length < 2) day = '0' + day; + + return [year, month, day].join('-'); + } + + // Get today's date + let today = new Date(); + let todayFormatted = formatDate(today); + + // Set the minimum date for fromDate input to today + let fromDateInput = document.getElementById('fromDate'); + fromDateInput.setAttribute('min', todayFormatted); + + // Add event listener to fromDate to update toDate min value and reset its value + fromDateInput.addEventListener('change', function () { + let selectedFromDate = this.value; + let toDateInput = document.getElementById('toDate'); + toDateInput.setAttribute('min', selectedFromDate); + toDateInput.value = ''; // Reset the value of toDate + }); + \ No newline at end of file diff --git a/src/main/resources/templates/admin/ongoingevents.html b/src/main/resources/templates/admin/ongoingevents.html index 8c29843e..741b8334 100644 --- a/src/main/resources/templates/admin/ongoingevents.html +++ b/src/main/resources/templates/admin/ongoingevents.html @@ -96,7 +96,6 @@ Action--> Hall Name Booking Id - Reason for Booking Start Date End Date No of Days @@ -122,7 +121,6 @@ --> - @@ -179,7 +177,6 @@ Action--> Hall Name Booking Id - Reason for Booking Start Date End Date No of Days @@ -206,7 +203,6 @@ - @@ -264,7 +260,6 @@ Hall Name Booking Id - Reason for Booking Start Date End Date No of Days @@ -291,7 +286,6 @@ - diff --git a/src/main/resources/templates/admin/settlement-list.html b/src/main/resources/templates/admin/settlement-list.html index eb37de65..d0a98170 100644 --- a/src/main/resources/templates/admin/settlement-list.html +++ b/src/main/resources/templates/admin/settlement-list.html @@ -448,7 +448,7 @@ style="padding: 0.45rem 0.45rem; color: green;" id="td_pending_amt"> 0 - + Collection Pending Status : diff --git a/src/main/resources/templates/admin/viewUploadNoc.html b/src/main/resources/templates/admin/viewUploadNoc.html index dc2962da..7fe32915 100644 --- a/src/main/resources/templates/admin/viewUploadNoc.html +++ b/src/main/resources/templates/admin/viewUploadNoc.html @@ -422,6 +422,7 @@ icon: 'warning', title: 'No File Selected', text: 'Please select a file to upload.', + allowOutsideClick: false, }); return; } @@ -449,6 +450,7 @@ icon: 'success', title: 'Success', text: 'NOC uploaded successfully!', + allowOutsideClick: false, }).then(() => { $('#uploadNocModal').modal('hide'); // Close the modal location.reload(); // Refresh the page @@ -460,6 +462,7 @@ icon: 'error', title: 'Upload Failed', text: 'Failed to upload NOC: ' + xhr.responseText, + allowOutsideClick: false, }); } }); diff --git a/src/main/resources/templates/caretaker/caretakerpage.html b/src/main/resources/templates/caretaker/caretakerpage.html index e416ef89..17b26693 100644 --- a/src/main/resources/templates/caretaker/caretakerpage.html +++ b/src/main/resources/templates/caretaker/caretakerpage.html @@ -130,7 +130,7 @@ + Material @@ -374,30 +374,12 @@ formData.append('ebAmount', ebAmount); var i = damageindex; - var isValid = true; $('#damageDetailsbody tr').each(function () { var assetName = $("#materials" + i).val(); var comments = $("#comments" + i).val(); var quantity = $("#quantity" + i).val(); var assetAmount = $("#totalDamageAmount" + i).html(); var assetImageInput = $("#damagePhoto" + i)[0].files[0]; // Assuming input type is file for assetImage - - // Skip validation if no material is selected - if (!assetName) { - i = i - 1; - return true; // Continue to the next row - } - - // Consolidated validation for selected material - if (!quantity || isNaN(quantity) || quantity <= 0 || - !assetAmount || isNaN(assetAmount) || assetAmount <= 0 || - !comments || !assetImageInput) { - alert("Please provide all valid details for row " + (i + 1) + "."); - isValid = false; - return false; // Exit the loop if validation fails - } - - formData.append('assetName', assetName); formData.append('comments', comments); formData.append('quantity', quantity); @@ -405,10 +387,6 @@ formData.append('assetImage', assetImageInput); i = i - 1; }); - if (!isValid) { - //alert("Please fix the errors before submitting the form."); - return false; - } $.ajax({ url: '/communityhall/careTaker/api/processEbDetailsAndDamage', type: 'POST', @@ -442,6 +420,7 @@ return false; } + let isCompressing = false; // Attach the validation function to file input change event $(document).on('change', '.damage-image', function () { diff --git a/src/main/resources/templates/caretaker/past-booking.html b/src/main/resources/templates/caretaker/past-booking.html index bb838a77..f38bd8a3 100644 --- a/src/main/resources/templates/caretaker/past-booking.html +++ b/src/main/resources/templates/caretaker/past-booking.html @@ -101,6 +101,7 @@ + diff --git a/src/main/resources/templates/caretaker/present-booking.html b/src/main/resources/templates/caretaker/present-booking.html index 4bff1e23..1da9b728 100644 --- a/src/main/resources/templates/caretaker/present-booking.html +++ b/src/main/resources/templates/caretaker/present-booking.html @@ -2,6 +2,8 @@ + + - - - - diff --git a/src/main/resources/templates/user/dashboard.html b/src/main/resources/templates/user/dashboard.html index 4bad49db..2f394722 100644 --- a/src/main/resources/templates/user/dashboard.html +++ b/src/main/resources/templates/user/dashboard.html @@ -181,1040 +181,1040 @@ - -
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+ +
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
- -
- -
- - - -
- -
-
-
- -
-
- -
- -
- - * * - -
-
-
-
- -
-
- -
-
-
- - -
+
+ +
+ +
+ + + +
+ +
+
+
+ +
+
+ +
+ +
+ + * * + +
+
+
+
+ +
+
+ +
+
+
+ + +
-
- - - - -
+ +
-
- - - - - - -
-
- - +
+
+ + -
+ Evening + +
-
-
- -
+ +
- -
- -
-

+ Now
+

- - -
- - -
-
-
-
-
-
- -
- +
- - -
- -
- - - - - - - - + + + + + + + - - - - + + + + + - + } + diff --git a/src/main/resources/templates/user/hallbookingform.html b/src/main/resources/templates/user/hallbookingform.html index 4d98a328..5b3e7873 100644 --- a/src/main/resources/templates/user/hallbookingform.html +++ b/src/main/resources/templates/user/hallbookingform.html @@ -1,13 +1,9 @@ - + - - - - @@ -1142,12 +1126,6 @@ Gcc Blocked
-
- - Temporary Blocked -

@@ -1278,14 +1256,13 @@ Blocked

- -
+

@@ -1427,13 +1404,6 @@ style="padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); background-color: #FFFFFF; border: 1px solid #CCCCCC;">
- - -
@@ -1517,7 +1487,7 @@ - Payment Closes in 03:00 + Payment Closes in 01:00 @@ -1683,8 +1653,7 @@
@@ -1738,7 +1707,6 @@ - diff --git a/src/main/resources/templates/user/viewhallform.html b/src/main/resources/templates/user/viewhallform.html index a2a6390e..6ac58760 100644 --- a/src/main/resources/templates/user/viewhallform.html +++ b/src/main/resources/templates/user/viewhallform.html @@ -4,6 +4,10 @@ + + + + @@ -1127,12 +1142,12 @@ Gcc Blocked -
+

@@ -1349,6 +1364,7 @@ initializeViewerJS(); getBookingCalendar(hallId); + //connectToWebSocket(hallId); // Set hall details in Step 2 and Step 3 $('#hallNameDisplayStep2').text(response.hallName); @@ -1421,7 +1437,7 @@ $("#startDateInput").datepicker("destroy"); for (var i = 0; i < response.length; i++) { var dateString = datepickerFormat(response[i].bdate); - window.bookingResponse[dateString] = [response[i].morningSlot, response[i].eveningSlot, response[i].is_blocked, response[i].temp_blocked]; + window.bookingResponse[dateString] = [response[i].morningSlot, response[i].eveningSlot, response[i].is_blocked]; } initializeDatepickerWithColors(hall_id); @@ -1438,52 +1454,194 @@ }); } + + /*function connectToWebSocket(hall_id) { + //console.log("Connecting to WebSocket for hall_id:", hall_id); + const socket = new SockJS('/ws'); + const stompClient = Stomp.over(socket); + + stompClient.connect({}, function () { + //console.log("Connected to WebSocket"); + + // Subscribe to the topic specific to the hall_id + const topic = `/topic/bookingCalendar/${hall_id}`; + stompClient.subscribe(topic, function (message) { + try { + const response = JSON.parse(message.body); // Parse the response + processBookingData(response, hall_id); // Process and update the calendar + } catch (error) { + console.error("Failed to parse message body: ", error); + } + }); + + // Request initial data for the hall + requestBookingData(hall_id, stompClient); + }, function (error) { + // console.error("WebSocket connection failed: ", error); + }); + } + + function requestBookingData(hall_id, stompClient) { + //console.log("Requesting booking data for hall_id:", hall_id); + + // Send hall_id as a JSON object + stompClient.send('/app/getPastData', {}, JSON.stringify({hall_id: hall_id})); + } + + function processBookingData(response, hall_id) { + //console.log("Processing booking data for hall_id:", hall_id); + //console.log("Response: ", response); + + window.bookingResponse = {}; + if (response && Array.isArray(response)) { + $("#startDateInput").datepicker("destroy"); + for (let i = 0; i < response.length; i++) { + const dateString = datepickerFormat(response[i].bdate); + window.bookingResponse[dateString] = [ + response[i].morningSlot, + response[i].eveningSlot, + response[i].is_blocked, + response[i].temp_blocked, + ]; + } + + initializeDatepickerWithColors(hall_id); + } else { + console.error("Invalid or empty response data."); + } + }*/ + + + // Function to update the end date and slot availability function initializeDatepickerWithColors(hallId) { - //console.log("Initializing Datepicker with hallId:", hallId); // Confirm hallId is passed here + // Destroy existing datepicker to avoid duplicate initialization $("#datepicker-container").datepicker("destroy"); + + // Initialize the datepicker $("#startDateInput,#datepicker-container").datepicker({ dateFormat: "yy-mm-dd", - minDate: "+7D", + minDate: 0, maxDate: "+6M", beforeShowDay: function (eDate) { - var today = new Date(); - var minDate = new Date(); - minDate.setDate(today.getDate() + 6); + const dateString = $.datepicker.formatDate("yy-mm-dd", eDate); + const bookingStatus = window.bookingResponse[dateString] || {}; - var dateString = $.datepicker.formatDate("yy-mm-dd", eDate); - var bookingStatus = window.bookingResponse[dateString]; + const currentDate = new Date(); + currentDate.setHours(0, 0, 0, 0); // Normalize current date to midnight + eDate.setHours(0, 0, 0, 0); // Normalize selected date to midnight - if (eDate < minDate) { - // Dates within the disabled range + // Logic for other dates + if (eDate < currentDate) { return [false, "highlight-disabled", "Slot not Available"]; } - if (bookingStatus) { - if (bookingStatus[2] === true) { - return [true, "highlight-blue", "GCC Blocked"]; - } else if (bookingStatus[3] === true) { - return [true, "highlight-lightpink disabled", "Temporary Blocked"] - } else if (bookingStatus[0] === false && bookingStatus[1] === false) { - return [true, "highlight-greens", "Slot Available"]; - } else if (bookingStatus[0] === true && bookingStatus[1] === true) { - return [true, "highlight-pink disabled", "Slot Occupied"]; - } else if (bookingStatus[0] === true && bookingStatus[1] === false) { - return [true, "highlight-yellow", "Evening Slot Available"]; - } else if (bookingStatus[0] === false && bookingStatus[1] === true) { - return [true, "highlight-violet", "Only Morning Slot Available"]; + const isToday = eDate.getTime() === currentDate.getTime(); + const currentHour = new Date().getHours(); + const isBefore6AM = currentHour < 6; + const isAfter2PM = currentHour >= 14; + + // Block 3-day logic for specific event types + const today = new Date(); + const blockedDate = new Date(today); + blockedDate.setDate(today.getDate() + 2); + + if (eDate <= blockedDate && window.isThreeDayBlock) { + return [false, "highlight-disabled", "Blocked due to event type"]; + } + + // Logic for today + if (isToday) { + if (isBefore6AM) { + // Before 6 AM: Allow full-day booking or adjust based on booking status + return handleBookingStatus(bookingStatus, "Full Day Available"); + } else if (isAfter2PM) { + // After 2 PM: Block all bookings + return handleAfter2PM(bookingStatus); + } else { + // Between 6 AM and 2 PM: Check status and disable morning slots + return handleMorningSlots(bookingStatus); } } - return [true, "highlight-greens", "Slot Available"]; + return handleBookingStatus(bookingStatus, "Slot Available"); }, }); - $('#selecthall').on('click', function () { + // Show datepicker when hall is selected + $('#selecthall').off('click').on('click', function () { $('#datepicker-container').datepicker('show'); }); + // Handle changes in the start date input + $("#startDateInput").on("change", function () { + const selectedDate = $(this).val(); + const bookingStatus = window.bookingResponse[selectedDate] || {}; + const currentDate = new Date(); + const currentHours = currentDate.getHours(); + const currentDateString = currentDate.toISOString().split("T")[0]; + + $("#startPeriodDropdown").val(0).prop("disabled", false); + $("#endPeriodDropdown").val(0).prop("disabled", false); + $("#numDaysCount").val(''); + validateForm(); + + if (selectedDate === currentDateString && currentHours >= 6) { + $("#startPeriodDropdown").val(2).prop("disabled", true); + } else if (bookingStatus[0]) { + $("#startPeriodDropdown").val(2).prop("disabled", true); + } else if (bookingStatus[1]) { + $("#startPeriodDropdown").val(1).prop("disabled", true); + } + updateEndDate(selectedDate); + }); + + // Event type change logic + $("#reasonforbooking").on("change", function () { + const selectedEventType = $(this).find("option:selected").text().trim(); + window.isThreeDayBlock = ["Commercial", "State Govt Event", "Central Govt Event"].includes(selectedEventType); + $("#datepicker-container").datepicker("refresh"); + }); + } + + function handleBookingStatus(bookingStatus, defaultMessage) { + if (bookingStatus[2]) { + return [true, "highlight-blue disabled", "GCC Blocked"]; + } else if (bookingStatus[3]) { + return [true, "highlight-lightpink disabled", "Temporary Blocked"]; + } else if (bookingStatus[0] && bookingStatus[1]) { + return [true, "highlight-pink disabled", "Slot Occupied"]; + } else if (bookingStatus[0] && !bookingStatus[1]) { + return [true, "highlight-yellow", "Evening Slot Available"]; + } else if (!bookingStatus[0] && bookingStatus[1]) { + return [true, "highlight-violet", "Only Morning Slot Available"]; + } + return [true, "highlight-greens", defaultMessage]; + } + + // Helper function: Handles logic after 2 PM + function handleAfter2PM(bookingStatus) { + if (bookingStatus[2]) { + return [true, "highlight-blue disabled", "GCC Blocked"]; + } else if (bookingStatus[0] || bookingStatus[1]) { + return [true, "highlight-pink disabled", "Slot Occupied"]; + } + return [false, "highlight-disabled", "Not Allowed to Book"]; + } + + // Helper function: Handles morning slots between 6 AM and 2 PM + function handleMorningSlots(bookingStatus) { + if (bookingStatus[2]) { + return [true, "highlight-blue disabled", "GCC Blocked"]; + } else if (bookingStatus[0] && bookingStatus[1]) { + return [false, "highlight-pink disabled", "Slot Occupied"]; + } else if (bookingStatus[0] && !bookingStatus[1]) { + return [true, "highlight-yellow", "Evening Slot Available"]; + } else if (!bookingStatus[0] && bookingStatus[1]) { + return [false, "highlight-disabled", "Slot Occupied"]; + } + return [true, "highlight-yellow", "Evening Slot Available"]; } function datepickerFormat(dateString) { diff --git a/src/main/resources/templates/user/viewhistory.html b/src/main/resources/templates/user/viewhistory.html index d60d89a9..a6423349 100644 --- a/src/main/resources/templates/user/viewhistory.html +++ b/src/main/resources/templates/user/viewhistory.html @@ -115,30 +115,6 @@ color: #000 !important; } - .highlight-blue .ui-state-default { - background: blue !important; - color: #FFF !important; - } - - .highlight-lightpink .ui-state-default { - background: lightpink !important; - color: #FFF !important; - } - - .highlight-lightpink a, - input[type=button]:disabled { - background-color: lightpink; - /* Pink highlight for disabled or booked dates */ - color: white; - } - - .highlight-blue a, - input[type=button]:disabled { - background-color: blue; - /* Pink highlight for disabled or booked dates */ - color: white; - } - .form-control[readonly] { background-color: white; } @@ -635,7 +611,7 @@ - + @@ -697,11 +673,25 @@ NOC

+ +

- --No Action-- + + Cancel + Booking +

+ +

--No Action-- @@ -719,7 +709,8 @@ th:if="${booking.booking_status == 'APPROVED'}"> Reschedule + th:onclick="openRescheduleModal([[${booking.booking_id}]], [[${booking.start_date}]], [[${booking.end_date}]],[[${booking.no_of_days}]], + [[${booking.hall_details_hall_id}]],[[${booking.starting_slot}]],[[${booking.ending_slot}]],[[${booking.reason}]])">Reschedule Booking

@@ -1094,7 +1085,7 @@ style="padding: 0.45rem 0.45rem; color: green;" id="td_pending_amt">0 - + @@ -1211,7 +1202,7 @@
@@ -1262,37 +1253,37 @@ + name="startingSlot" readonly> + name="startingSlot" required>
+ name="endDateInput" readonly> + name="endDateInput" readonly>
+ style="background-color:#008000;">

Day
(Available)

+ style="background-color: #ac2bac;">

Morning
(Available)

+ style="background-color:#FFEA00;">

Evening
(Available)

+ style="background-color: red;">

Not Available

@@ -1300,20 +1291,22 @@ style="background-color: blue;">

GCC Blocked

-
+
@@ -1385,8 +1378,8 @@ - - + + @@ -1871,7 +1864,7 @@ var temp_total = parseFloat($("#td_settel_amt").html()); var settleAmount = temp_total - totalAmount; - if (settleAmount < 0) { + if (settleAmount < 0) { var pendingstatus=data.settlement.collectionStatus $("#td_settel_amt").html(0.00); $("#pendingcolumn").show(); @@ -1884,7 +1877,7 @@ $("#pendingcolumn").hide(); $("#collectionstatuscolumn").hide(); $("#td_settel_amt").css("color", "green"); // Set color to green for positive amounts - } + } } @@ -2031,7 +2024,7 @@ }); } } - function openRescheduleModal(bookingId, startDate, endDate, noOfDays, hallId, startingSlot, endingSlot) { + function openRescheduleModal(bookingId, startDate, endDate, noOfDays, hallId, startingSlot, endingSlot, reason) { // Function to map slot values to their text representation function getSlotText(slot) { return slot === 1 ? 'Morning' : 'Evening'; @@ -2060,14 +2053,14 @@ document.getElementById("endingSlotText").value = getSlotText(endingSlot); // Optionally, fetch and update calendar or availability based on hallId - getBookingCalendar(hallId); + getBookingCalendar(hallId, reason); // Show the modal $('#bookingRescheduleModal').modal('show'); } - function getBookingCalendar(hall_id) { + function getBookingCalendar(hall_id, reason) { // Make an AJAX call to fetch booking data $.ajax({ type: 'GET', @@ -2082,12 +2075,12 @@ $("#startDateInput").datepicker("destroy"); for (var i = 0; i < response.length; i++) { var dateString = datepickerFormat(response[i].bdate); - window.bookingResponse[dateString] = [response[i].morningSlot, response[i].eveningSlot, response[i].is_blocked, response[i].temp_blocked ]; + window.bookingResponse[dateString] = [response[i].morningSlot, response[i].eveningSlot]; } - initializeDatepickerWithColors(hall_id); + initializeDatepickerWithColors(hall_id, reason); if (response.length == 0) { - initializeDatepickerWithColors(hall_id); + initializeDatepickerWithColors(hall_id, reason); } } else { console.error('Invalid or empty response data.'); @@ -2098,42 +2091,57 @@ } }); } - function initializeDatepickerWithColors(hallId) { // Confirm hallId is passed here + + function initializeDatepickerWithColors(hallId, reason) { // Confirm hallId is passed here $("#datepicker-container").datepicker("destroy"); $("#startDateInput,#datepicker-container").datepicker({ dateFormat: "yy-mm-dd", - minDate: "+7D", + minDate:0, maxDate: "+6M", beforeShowDay: function (eDate) { - var today = new Date(); - var minDate = new Date(); - minDate.setDate(today.getDate() + 6); - var dateString = $.datepicker.formatDate("yy-mm-dd", eDate); - var bookingStatus = window.bookingResponse[dateString]; + const dateString = $.datepicker.formatDate("yy-mm-dd", eDate); + const bookingStatus = window.bookingResponse[dateString] || {}; - if (eDate < minDate) { - // Dates within the disabled range + const currentDate = new Date(); + currentDate.setHours(0, 0, 0, 0); // Normalize current date to midnight + eDate.setHours(0, 0, 0, 0); // Normalize selected date to midnight + + // Logic for other dates + if (eDate < currentDate) { return [false, "highlight-disabled", "Slot not Available"]; } - if (bookingStatus) { - if (bookingStatus[2] === true) { - return [true, "highlight-blue disabled", "GCC Blocked"]; - } else if (bookingStatus[3] === true) { - return [true, "highlight-lightpink disabled", "Temporary Blocked"] - }else if (bookingStatus[0] === false && bookingStatus[1] === false) { - return [true, "highlight-greens", "Slot Available"]; - } else if (bookingStatus[0] === true && bookingStatus[1] === true) { - return [true, "highlight-pink disabled", "Slot Occupied"]; - } else if (bookingStatus[0] === true && bookingStatus[1] === false) { - return [true, "highlight-yellow", "Evening Slot Available"]; - } else if (bookingStatus[0] === false && bookingStatus[1] === true) { - return [true, "highlight-violet", "Only Morning Slot Available"]; + const isToday = eDate.getTime() === currentDate.getTime(); + const currentHour = new Date().getHours(); + const isBefore6AM = currentHour < 6; + const isAfter2PM = currentHour >= 14; + + // Block 3-day logic for specific event types + const today = new Date(); + const blockedDate = new Date(today); + blockedDate.setDate(today.getDate() + 2); + + const isThreeDayBlock = ["Commercial", "State Govt Event", "Central Govt Event"].includes(reason); + if (eDate <= blockedDate && isThreeDayBlock) { + return [false, "highlight-disabled", "Blocked due to event type"]; + } + + // Logic for currentdate + if (isToday) { + if (isBefore6AM) { + // Before 6 AM: Allow full-day booking or adjust based on booking status + return handleBookingStatus(bookingStatus, "Full Day Available"); + } else if (isAfter2PM) { + // After 2 PM: Block all bookings + return handleAfter2PM(bookingStatus); + } else { + // Between 6 AM and 2 PM: Check status and disable morning slots + return handleMorningSlots(bookingStatus); } } - return [true, "highlight-greens", "Slot Available"]; + return handleBookingStatus(bookingStatus, "Slot Available"); }, }); @@ -2145,6 +2153,46 @@ var noofdays = document.getElementById("noOfDaysInput").value; updateEndDate(selectedDate, noofdays, startingSlot, endingSlot); }); + + } + + function handleBookingStatus(bookingStatus, defaultMessage) { + if (bookingStatus[2]) { + return [true, "highlight-blue disabled", "GCC Blocked"]; + } else if (bookingStatus[3]) { + return [true, "highlight-lightpink disabled", "Temporary Blocked"]; + } else if (bookingStatus[0] && bookingStatus[1]) { + return [true, "highlight-pink disabled", "Slot Occupied"]; + } else if (bookingStatus[0] && !bookingStatus[1]) { + return [true, "highlight-yellow", "Evening Slot Available"]; + } else if (!bookingStatus[0] && bookingStatus[1]) { + return [true, "highlight-violet", "Only Morning Slot Available"]; + } + return [true, "highlight-greens", defaultMessage]; + } + + // Helper function: Handles logic after 2 PM + function handleAfter2PM(bookingStatus) { + if (bookingStatus[2]) { + return [true, "highlight-blue disabled", "GCC Blocked"]; + } else if (bookingStatus[0] || bookingStatus[1]) { + return [true, "highlight-pink disabled", "Slot Occupied"]; + } + return [false, "highlight-disabled", "Not Allowed to Book"]; + } + + // Helper function: Handles morning slots between 6 AM and 2 PM + function handleMorningSlots(bookingStatus) { + if (bookingStatus[2]) { + return [true, "highlight-blue disabled", "GCC Blocked"]; + } else if (bookingStatus[0] && bookingStatus[1]) { + return [true, "highlight-pink disabled", "Slot Occupied"]; + } else if (bookingStatus[0] && !bookingStatus[1]) { + return [true, "highlight-yellow", "Evening Slot Available"]; + } else if (!bookingStatus[0] && bookingStatus[1]) { + return [false, "highlight-disabled", "Slot Occupied"]; + } + return [true, "highlight-yellow", "Evening Slot Available"]; } function updateEndDate(startDate, noofdays, startingSlot, endingSlot) { @@ -2592,14 +2640,14 @@ function toggleChat() { function sendMessage() { const userInput = document.getElementById('userInput'); const message = userInput.value.trim(); - + if (message) { // Create message element const chatBody = document.getElementById('chat-body'); const userMessage = document.createElement('div'); userMessage.className = 'user-message'; userMessage.textContent = message; - + chatBody.appendChild(userMessage); chatBody.scrollTop = chatBody.scrollHeight; // Auto-scroll to bottom @@ -2617,7 +2665,7 @@ function sendMessage() { const responseMessage = document.createElement('div'); responseMessage.className = 'bot-message'; responseMessage.textContent = data.response; - + chatBody.appendChild(responseMessage); chatBody.scrollTop = chatBody.scrollHeight; });
Collection Pending Status :
S.NOBooking IDAmountBooking IDAmount Date Transaction ID Status