Browse Source

Enhancement added and Bugs fixed

master
kanimozhi 2 years ago
parent
commit
3e6470ef67
  1. 1
      src/main/java/com/gcc/communityHall/controller/AdminAPIController.java
  2. 71
      src/main/java/com/gcc/communityHall/controller/Admincontroller.java
  3. 73
      src/main/java/com/gcc/communityHall/controller/HeadquartersController.java
  4. 2
      src/main/java/com/gcc/communityHall/controller/OfficerAPIController.java
  5. 231
      src/main/java/com/gcc/communityHall/controller/UserAPIController.java
  6. 24
      src/main/java/com/gcc/communityHall/controller/UserController.java
  7. 25
      src/main/java/com/gcc/communityHall/entity/BookingCalendar.java
  8. 16
      src/main/java/com/gcc/communityHall/paymentService/controller/PaymentAPIController.java
  9. 2
      src/main/java/com/gcc/communityHall/paymentService/controller/PaymentController.java
  10. 16
      src/main/java/com/gcc/communityHall/paymentService/repository/TransactionResponseRepository.java
  11. 9
      src/main/java/com/gcc/communityHall/paymentService/service/PaymentGatewayServiceImpl.java
  12. 19
      src/main/java/com/gcc/communityHall/repository/BookingCalendarRepository.java
  13. 66
      src/main/java/com/gcc/communityHall/repository/BookingDetailsRepository.java
  14. 1
      src/main/java/com/gcc/communityHall/repository/HallDetailsRepository.java
  15. 3
      src/main/java/com/gcc/communityHall/service/BookingService.java
  16. 454
      src/main/java/com/gcc/communityHall/service/Impl/BookingServiceImpl.java
  17. 2
      src/main/resources/templates/admin/adminpage.html
  18. 6
      src/main/resources/templates/admin/caretakerpage.html
  19. 51
      src/main/resources/templates/admin/gccblocking.html
  20. 6
      src/main/resources/templates/admin/ongoingevents.html
  21. 3
      src/main/resources/templates/admin/viewUploadNoc.html
  22. 25
      src/main/resources/templates/caretaker/caretakerpage.html
  23. 1
      src/main/resources/templates/caretaker/past-booking.html
  24. 8
      src/main/resources/templates/caretaker/present-booking.html
  25. 14
      src/main/resources/templates/fragments/PaymentScript.html
  26. 6
      src/main/resources/templates/fragments/headquartersMenu.html
  27. 20
      src/main/resources/templates/fragments/logRegiOtpScript.html
  28. 2
      src/main/resources/templates/fragments/loginscript.html
  29. 4
      src/main/resources/templates/fragments/resetpassword.html
  30. 10
      src/main/resources/templates/headquarters/bookingwaiting.html
  31. 1387
      src/main/resources/templates/headquarters/gccblocking.html
  32. 2
      src/main/resources/templates/headquarters/headquarterspage.html
  33. 8
      src/main/resources/templates/headquarters/ongoingevents.html
  34. 3
      src/main/resources/templates/headquarters/viewUploadNoc.html
  35. 2
      src/main/resources/templates/officer/booking-list.html
  36. 2
      src/main/resources/templates/officer/rejected-list.html
  37. 4
      src/main/resources/templates/officiallogin.html
  38. 620
      src/main/resources/templates/user/calculatehallamount.html
  39. 16
      src/main/resources/templates/user/collectionpending.html
  40. 5
      src/main/resources/templates/user/dashboard.html
  41. 533
      src/main/resources/templates/user/hallbookingform.html
  42. 212
      src/main/resources/templates/user/viewhallform.html
  43. 166
      src/main/resources/templates/user/viewhistory.html

1
src/main/java/com/gcc/communityHall/controller/AdminAPIController.java

@ -1486,7 +1486,6 @@ public class AdminAPIController {
}
}
@PostMapping("/uploadnoc")
public ResponseEntity<String> uploadnoc(@RequestParam("nocFile") MultipartFile file,
@RequestParam("bookingid") int bookingId) {

71
src/main/java/com/gcc/communityHall/controller/Admincontroller.java

@ -151,7 +151,6 @@ public class Admincontroller {
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 {
@ -531,26 +530,6 @@ public class Admincontroller {
}
}
/* @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<BookingDetails> 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");
@ -568,25 +547,6 @@ public class Admincontroller {
}
}
@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<BookingDetails> 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";
}
}
@PostMapping("/getReport")
public String generateReport(Model model,
@RequestParam(name = "FromDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) String fromDate,
@ -1005,12 +965,10 @@ public class Admincontroller {
@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<BookingDetails> 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<BookingDetails> settlement = bookingDetailsRepository.findAllSettlementRejected();
model.addAttribute("title", "Settlement Rejected");
model.addAttribute("adminname", adminname);
model.addAttribute("rejectSettlementlist", settlement);
return "admin/settlement-reject";
} else {
@ -1058,5 +1015,25 @@ public class Admincontroller {
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<BookingDetails> 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";
}
}
}

73
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;
@ -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<GccBlockingDate> gccBlocked = blockingDateRepository.findAllBlocked();
// Ensure distinct by hallId, blockingReason, startDate, and endDate
List<GccBlockingDate> 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<Integer, Integer> hallCountMap = new HashMap<>();
for (GccBlockingDate blockedDate : uniqueGccBlockingDates) {
// Parse and count unique hall IDs
String hallIds = blockedDate.getHallId();
if (hallIds != null && !hallIds.isEmpty()) {
Set<String> 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 <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Set<Object> 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";
}
}

2
src/main/java/com/gcc/communityHall/controller/OfficerAPIController.java

@ -226,7 +226,6 @@ public class OfficerAPIController {
}
}
@Operation(
summary = "Settlement APPROVED REST API",
description = "REST API for Updating the Refund Status to Approved by Settlement Id If the settlement is Approved"
@ -337,7 +336,6 @@ public class OfficerAPIController {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@PostMapping("/toggleStatus")
public ResponseEntity<String> toggleUserStatus(
@RequestParam Integer userId,

231
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;
@ -181,14 +175,9 @@ public class UserAPIController {
@Autowired
private TransRefundResRepository transRefundResRepository;
private final SimpMessagingTemplate messagingTemplate;
@Autowired
public UserAPIController(@Value("${file.upload.directory}") String uploadDirectory,
SimpMessagingTemplate messagingTemplate, BookingService bookingService) {
public UserAPIController(@Value("${file.upload.directory}") String uploadDirectory) {
this.uploadDirectory = uploadDirectory;
this.messagingTemplate = messagingTemplate;
// this.bookingService = bookingService;
}
@Operation(
@ -249,7 +238,8 @@ public class UserAPIController {
//System.out.println(purpose);
//System.out.print("\n MobileNo---:"+mobileNo);
Random rand = new Random();
int otp = rand.nextInt(90000) + 10000;
// int otp = 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();
@ -260,7 +250,7 @@ public class UserAPIController {
System.out.println(urlString);
System.out.print("\n urlString---: "+urlString);
String bodyMessage = "";
try {
/*try {
RestTemplate restTemplate = new RestTemplate();
String Response = restTemplate.getForObject(urlString, String.class);
bodyMessage=Response;
@ -277,7 +267,7 @@ public class UserAPIController {
} catch (Exception e) {
// System.out.print("ERROR in Sending---: "+e);
bodyMessage = "Error";
}
}*/
HttpSession session = request.getSession();
session.setAttribute("otp", otp);
@ -327,7 +317,6 @@ public class UserAPIController {
return "Error";
}
}
@GetMapping(value = "/verifyofficialOTP")
public String verifyOtp(HttpServletRequest request, @RequestParam String otp) {
HttpSession session = request.getSession();
@ -404,6 +393,7 @@ public class UserAPIController {
}
@GetMapping("/checkEmployee")
public Map<String, Boolean> checkEmployee(@RequestParam String id) {
boolean isRegistered = usersRepository.existsByGovernmentId(id);
@ -453,21 +443,6 @@ public class UserAPIController {
return data;
}
/*@MessageMapping("/getPastData")
@SendTo("/topic/bookingCalendar")
public List<BookingCalendar> getPastData(String payload) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(payload);
int hall_id = jsonNode.get("hall_id").asInt();
List<BookingCalendar> 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"
@ -1056,7 +1031,6 @@ public class UserAPIController {
public ResponseEntity<?> saveTheBookingDetails2(HttpServletRequest request) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Map<String,Object> bookingDetails = splitFormData(multipartRequest);
// System.out.println("Bc Id 1..............."+bookingDetails.get("bcId"));
Map<String, Object> saveBookingDetails = bookingService.saveBookingDetails(bookingDetails);
return ResponseEntity.ok(saveBookingDetails);
}
@ -1284,7 +1258,6 @@ public class UserAPIController {
Map<String, Object> saveCounterBooking = counterService.saveCounterBooking(bookingDetails);
return ResponseEntity.ok(saveCounterBooking);
}
@GetMapping("/checkAvail")
public List<HallDetails> checkAvail(@RequestParam("fromDate") String fromDate,
@RequestParam("toDate") String toDate,
@ -1319,7 +1292,8 @@ public class UserAPIController {
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) {
}
else if(data.get(i).isMorningSlot()==false) {
continue;
}
} else if ((starting.equals(ending) || starting.equals("evening") && ending.equals("morning")) && !toDate.equals(fromDate)) {
@ -1334,7 +1308,8 @@ public class UserAPIController {
continue;
}
} else if (toDate.equals(data.get(i).getBdate().toString()) && data.get(i).isMorningSlot() == false) {
}
else if(toDate.equals(data.get(i).getBdate().toString()) && data.get(i).isMorningSlot()==false){
if(checkHallId == data.get(i).getHallId() && checkAvail==false){
checkHallId=data.get(i).getHallId();
continue;
@ -1346,7 +1321,9 @@ public class UserAPIController {
if(checkHallId == data.get(i).getHallId()){
continue;
}
} else if (toDate.equals(data.get(i).getBdate().toString()) && data.get(i).isMorningSlot() == false) {
}
else if(toDate.equals(data.get(i).getBdate().toString()) && data.get(i).isMorningSlot()==false){
if(checkHallId == data.get(i).getHallId() && checkAvail==false){
checkHallId=data.get(i).getHallId();
continue;
@ -1357,13 +1334,15 @@ public class UserAPIController {
if(checkHallId == data.get(i).getHallId()){
continue;
}
} else if (toDate.equals(data.get(i).getBdate().toString()) && data.get(i).isEveningSlot() == false) {
}
else if(toDate.equals(data.get(i).getBdate().toString()) && data.get(i).isEveningSlot()==false){
if(checkHallId == data.get(i).getHallId() && checkAvail==false){
checkHallId=data.get(i).getHallId();
continue;
}
}
} else {
}
else{
if(checkHallId == data.get(i).getHallId()) {
checkAvail = true;
}
@ -1566,6 +1545,7 @@ public class UserAPIController {
}
if (bookingDetails.getBookingStatus() == BookingStatus.GCC_BLOCKED){
Map<String ,Object> gccBlockedDetail = new HashMap<>();
gccBlockedDetail.put("status","GCC_BLOCKED");
@ -1594,9 +1574,7 @@ public class UserAPIController {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("File upload failed: " + e.getMessage());
}
}
@GetMapping("/calculatehallamount")
/*@GetMapping("/calculatehallamount")
public ResponseEntity<Map<String, Object>> getHallDetailsConcession(
@RequestParam int numDays,
@RequestParam(value = "startPeriod", required = false) String startPeriod,
@ -1664,7 +1642,7 @@ public class UserAPIController {
response.put("totalAmount", totalAmount);
response.put("discountAmount", discountAmount);
} else if ("CGE".equals(reasonforBooking)) {
/*response.put("discount", hallDetails.getCGEdiscount());
response.put("discount", hallDetails.getCGEdiscount());
discountAmount = (amount * hallDetails.getCGEdiscount()) / 100.0;
totalAmount = discountAmount + totalDepositAmount + (discountAmount * gstRate / 100);
response.put("amount", amount);
@ -1672,8 +1650,121 @@ public class UserAPIController {
response.put("depositAmount", totalDepositAmount);
double gstValue = gstRate * discountAmount / 100;
response.put("gst", gstValue);
response.put("discountAmount", discountAmount);*/
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<Map<String, Object>> 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<HallDetails> 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<String, Object> response = new HashMap<>();
double amount = calculateAmount(numDays, startPeriod, endPeriod, fullDayAmount, halfDayAmount);
double totalDepositAmount = calculateDepositAmount(numDays, startPeriod, endPeriod, depositAmount);
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)) {
double cleaningCharges = hallDetails.getHallDetailsConcession().get(0).getFullDayCleaningcharges();
double pasystem=hallDetails.getHallDetailsConcession().get(0).getFulldayPAsystem();
double ebCharges=hallDetails.getHallDetailsConcession().get(0).getFulldayEBcharges();
@ -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;
@ -1772,5 +1862,52 @@ public class UserAPIController {
model.addAttribute("userName",userSession.getDispayName());
return bookingsDetails;
}
@GetMapping("/checkQueue")
public ResponseEntity<List<BookingDetails>> checkQueue(
@RequestParam String bookingDate,
@RequestParam Long hallId) {
try {
List<BookingDetails> 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;
// 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;
}
}

24
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;
@ -35,7 +34,8 @@ import com.gcc.communityHall.service.Impl.WhatsappMsgServiceImpl;
@RequestMapping(value = {"/communityhall/user", "/communityhall", "", "/"})
public class UserController {
@Autowired UserSession userSession;
@Autowired
UserSession userSession;
@Autowired
private BookingService bookingService;
@ -236,21 +236,10 @@ public class UserController {
@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);
@ -304,6 +293,7 @@ public class UserController {
model.addAttribute("userName", userSession.getDispayName());
return "user/collectionpending";
}
@GetMapping("/collectionpendingacknowledgement")
public String viewCollectionpendingAck(Model model, int bookingId) {
BookingDetails bookingsDetails = bookingService.getBookingsById(bookingId);
@ -312,5 +302,13 @@ public class UserController {
return "user/extraebdamageamountack";
}
@GetMapping("/viewhallform")
public String viewhallform(Model model) {
String username = userSession.getDispayName();
model.addAttribute("userName", username);
return "user/viewhallform";
}
}

25
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,13 +33,10 @@ 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() {
return bdate;
}
@ -112,12 +109,12 @@ 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() {
@ -126,8 +123,7 @@ public class BookingCalendar {
}
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;
}

16
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",
@ -144,11 +140,8 @@ public class PaymentAPIController {
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();
@ -159,6 +152,7 @@ public class PaymentAPIController {
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
@ -174,12 +168,8 @@ public class PaymentAPIController {
hs.put("consumerEmailId",consumerEmailId);
hs.put("consumerId",consumerId);
hs.put("error", false);
} else{
hs.put("status", "slotOccupied");
return hs;
}
} else {
else {
hs.put("error", true);
}

2
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);

16
src/main/java/com/gcc/communityHall/paymentService/repository/TransactionResponseRepository.java

@ -24,20 +24,8 @@ public interface TransactionResponseRepository extends JpaRepository<Transaction
Optional<TransactionResponse> findByTxansactionIdAndStatusCode(String txansactionId,String statusCode );
Optional<TransactionResponse> findByBookingIdAndStatusCode(int bookingId, String statusCode);
Optional<TransactionResponse> 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<Object[]> 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<Transaction
@Param("toDate") String toDate,
@Param("bookingId") Long bookingId,
@Param("hallId") Long hallId);
*/
// @Transactional

9
src/main/java/com/gcc/communityHall/paymentService/service/PaymentGatewayServiceImpl.java

@ -248,8 +248,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<BookingDetails> 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<BookingDetails> bookingsDetails=bookingDetailsRepository.findById(bookingId);
BookingDetails bookingDetails=bookingsDetails.get();
@ -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());

19
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<BookingCalendar,Integer> {
@ -62,17 +60,6 @@ public interface BookingCalendarRepository extends JpaRepository<BookingCalendar
void updateBdateByBookingIdAndDate(@Param("newDate") LocalDate newDate, @Param("bookingId") String bookingId, @Param("currentDate") LocalDate currentDate);
Optional<BookingCalendar> 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<Object[]> 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<Object[]> 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);
}

66
src/main/java/com/gcc/communityHall/repository/BookingDetailsRepository.java

@ -13,27 +13,25 @@ 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<BookingDetails, Integer> {
@Query(value = "SELECT * FROM booking_details where booking_status='GCC_BLOCKED'", nativeQuery = true)
List<BookingDetails> getGccBlockedList();
@Query(value = "SELECT * FROM booking_details where booking_status='APPROVED'", nativeQuery = true)
List<BookingDetails> getAllApprovedList();
@Query(value = "SELECT * FROM booking_details where booking_status='REJECTED'", nativeQuery = true)
List<BookingDetails> getAllRejectingList();
@Query(value = "SELECT * FROM booking_details where booking_status='WAITING_FOR_NOC' order by booking_id", nativeQuery = true)
List<BookingDetails> getAllwaitingNOC();
@Query(value = "SELECT * FROM booking_details where booking_status='WAITING_FOR_NOC_APPROVAL'", nativeQuery = true)
List<BookingDetails> 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)
@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<BookingDetails> findByFromDateBetweenAndToDateBetweenAndHallIdIn(LocalDate fromDate, LocalDate toDate, List<Long> hallIds);
@ -61,6 +59,8 @@ public interface BookingDetailsRepository extends JpaRepository<BookingDetails,I
// List<BookingDetails> 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<BookingDetails> findPastEventsByHallId(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<BookingDetails> 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<BookingDetails> findPastEventsByHallId(@Param("hallId") Integer hallId);
@ -78,18 +78,24 @@ List<BookingDetails> findPastEventsByHallId(@Param("hallId") 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"
+ "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<BookingDetails> 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<BookingDetails> 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<BookingDetails> getAllSettlementList();
//yoga
@Query(value = "SELECT " +
"u.user_id AS userId, " +
@ -113,7 +119,6 @@ List<BookingDetails> findPastEventsByHallId(@Param("hallId") Integer hallId);
List<Object[]> getBookingUserDetailsReport(@Param("fromDate") String fromDate, @Param("toDate") String toDate);
@Query(value = "SELECT " +
"h.hall_name AS HallName, " +
"h.hall_Incharge_name AS InchargeName, " +
@ -280,7 +285,6 @@ List<BookingDetails> findPastEventsByHallId(@Param("hallId") Integer hallId);
List<Map<String, Object>> 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"
@ -317,9 +321,9 @@ List<BookingDetails> findPastEventsByHallId(@Param("hallId") Integer hallId);
+ " 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"
+ " 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"
@ -335,6 +339,7 @@ List<BookingDetails> findPastEventsByHallId(@Param("hallId") Integer hallId);
+ "ORDER BY bd.start_date DESC;\r\n"
+ "", nativeQuery = true)
List<Map<String, Object>> getAllBookingEventsByUserId(Integer userId);
//counter
@Query(value = "SELECT bd.*, " +
"hd.zone AS hall_zone, " +
@ -364,6 +369,7 @@ List<BookingDetails> findPastEventsByHallId(@Param("hallId") Integer hallId);
@Query("SELECT b FROM BookingDetails b JOIN FETCH b.settlement s WHERE b.refundStatus = 'APPROVED'")
List<BookingDetails> findAllWithApprovedRefundStatus();
@Query("SELECT b FROM BookingDetails b JOIN FETCH b.settlement s WHERE b.refundStatus = 'INITIATED'")
List<BookingDetails> findByBookingDetailsRefundStatus();
@ -379,6 +385,10 @@ List<BookingDetails> findPastEventsByHallId(@Param("hallId") Integer hallId);
@Query("SELECT b FROM BookingDetails b JOIN FETCH b.settlement s WHERE b.refundStatus = 'REJECTED' and b.hallDetails.zone=:zone")
List<BookingDetails> findSettlementRejectedByZone(String zone);
@Query("SELECT b FROM BookingDetails b JOIN FETCH b.settlement s WHERE b.refundStatus = 'REJECTED'")
List<BookingDetails> findAllSettlementRejected();
@Query("SELECT b FROM BookingDetails b WHERE b.refundStatus = 'WAITING' AND b.bookingStatus = 'CANCELED' AND b.hallDetails.zone = :zone")
List<BookingDetails> findCancelledListByZone(@Param("zone") String zone);
@ -397,15 +407,19 @@ List<BookingDetails> findPastEventsByHallId(@Param("hallId") Integer hallId);
@Query(value = "SELECT * FROM booking_details WHERE refund_status = 'APPROVED' AND booking_status IN ('GCC_BLOCKED', 'REJECTED')", nativeQuery = true)
List<BookingDetails> findRejectedList();
@Query(value = "SELECT * FROM booking_details WHERE refund_status = 'INITIATED' AND booking_status = 'CANCELED'", nativeQuery = true)
List<BookingDetails> findInitiatedCancelledList();
@Query(value = "SELECT * FROM booking_details WHERE refund_status = 'INITIATED' AND booking_status IN ('GCC_BLOCKED', 'REJECTED')", nativeQuery = true)
List<BookingDetails> findInitiatedRejectedList();
@Query(value = "SELECT * FROM booking_details WHERE refund_status IN ('COMPLETED','CLOSED') AND booking_status = 'COMPLETED'", nativeQuery = true)
List<BookingDetails> findSettlementCompletedList();
@Query(value = "SELECT * FROM booking_details WHERE refund_status = 'COMPLETED' AND booking_status = 'CANCELED'", nativeQuery = true)
List<BookingDetails> findCancelledCompletedList();
@Query(value = "SELECT * FROM booking_details WHERE refund_status = 'COMPLETED' AND booking_status IN ('GCC_BLOCKED', 'REJECTED')", nativeQuery = true)
List<BookingDetails> findRejectedSettlementCompletedList();
@ -579,7 +593,6 @@ List<BookingDetails> findPastEventsByHallId(@Param("hallId") Integer hallId);
"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 " +
"FROM booking_details b " +
@ -607,7 +620,6 @@ List<BookingDetails> findPastEventsByHallId(@Param("hallId") Integer hallId);
"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 " +
"FROM booking_details b " +
@ -635,7 +647,6 @@ List<BookingDetails> findPastEventsByHallId(@Param("hallId") Integer hallId);
"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 " +
"FROM booking_details b " +
@ -663,7 +674,6 @@ List<BookingDetails> findPastEventsByHallId(@Param("hallId") Integer hallId);
"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 main_gst_amount, NULL AS PAST_Events, NULL AS FUTURE_Events " +
@ -689,7 +699,6 @@ List<BookingDetails> findPastEventsByHallId(@Param("hallId") Integer hallId);
"UNION ALL " +
"SELECT 'paymentStatus' AS category, " +
" p.payment_status AS `key`, " +
@ -735,7 +744,6 @@ List<BookingDetails> findPastEventsByHallId(@Param("hallId") Integer hallId);
"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, " +
@ -1023,6 +1031,7 @@ List<BookingDetails> findPastEventsByHallId(@Param("hallId") Integer hallId);
"AND hd.zone = :zone " +
"AND p.payment_status='Success' ", nativeQuery = true)
List<Object[]> 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, " +
@ -1048,7 +1057,6 @@ List<BookingDetails> findPastEventsByHallId(@Param("hallId") Integer hallId);
List<Object[]> 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, " +
@ -1332,6 +1340,7 @@ List<BookingDetails> findFutureEventsList();
"AND DATE(bd.end_date) <= :toDate " +
"AND (:refundStatus IS NULL OR bd.refund_status = :refundStatus) ", nativeQuery = true)
List<BookingDetails> 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")
@ -1381,31 +1390,46 @@ List<BookingDetails> findFutureEventsList();
@Query("SELECT b FROM BookingDetails b WHERE b.refundStatus = 'FAILURE' AND b.bookingStatus = 'APPROVED' AND b.hallDetails.zone = :zone")
List<BookingDetails> findSettlementRefundFailedByZone(String zone);
@Query("SELECT b FROM BookingDetails b WHERE b.refundStatus = 'FAILURE' AND b.bookingStatus = 'CANCELED' AND b.hallDetails.zone = :zone")
List<BookingDetails> 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<BookingDetails> 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<BookingDetails> findSettlementCompletedListbyzone(String zone);
@Query("SELECT b FROM BookingDetails b WHERE b.bookingStatus = 'CANCELED' AND b.refundStatus = 'COMPLETED' AND b.hallDetails.zone = :zone")
List<BookingDetails> 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<BookingDetails> findRejectedSettlementCompletedListbyzone(String zone);
@Query("SELECT b FROM BookingDetails b JOIN FETCH b.settlement s WHERE b.refundStatus = 'WAITING'")
List<BookingDetails> findAllSettlementPending();
@Query("SELECT b FROM BookingDetails b WHERE b.refundStatus = 'WAITING' AND b.bookingStatus = 'CANCELED'")
List<BookingDetails> findAllSettlementCancelledList();
@Query("SELECT b FROM BookingDetails b WHERE b.refundStatus = 'WAITING' AND b.bookingStatus IN ('REJECTED','GCC_BLOCKED')")
List<BookingDetails> findAllSettlementRejectedList();
@Query("SELECT b FROM BookingDetails b WHERE b.refundStatus = 'FAILURE' AND b.bookingStatus = 'APPROVED'")
List<BookingDetails> findAllSettlementRefundFailed();
@Query("SELECT b FROM BookingDetails b WHERE b.refundStatus = 'FAILURE' AND b.bookingStatus = 'CANCELED'")
List<BookingDetails> findAllRefundFaileCancelledList();
@Query("SELECT b FROM BookingDetails b WHERE b.refundStatus = 'FAILURE' AND b.bookingStatus IN ('REJECTED','GCC_BLOCKED')")
List<BookingDetails> findAllRefundFaileRejectedList();
@Query("SELECT b FROM BookingDetails b JOIN FETCH b.settlement s WHERE b.refundStatus = 'REJECTED'")
List<BookingDetails> 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<BookingDetails> getAllSettlementList();}
@Query(value = "SELECT * FROM booking_details WHERE booking_date = :bookingDate AND hall_details_hall_id = :hallId", nativeQuery = true)
List<BookingDetails> 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<BookingDetails> getAllwaitingNOC();
}

1
src/main/java/com/gcc/communityHall/repository/HallDetailsRepository.java

@ -43,6 +43,7 @@ public interface HallDetailsRepository extends JpaRepository<HallDetails,Integer
@Query(value = "SELECT * FROM hall_details WHERE is_active = 1 order by hall_name asc", nativeQuery = true)
List<HallDetails> findActiveHalls();
//admin dashboard
@Query(nativeQuery = true, value ="SELECT SUM(CASE WHEN b.booking_status = 'APPROVED' THEN 1 ELSE 0 END) AS approvedCount,\r\n"

3
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);
@ -151,4 +150,6 @@ List<Object[]> getAllExtraPaymentsDetails( String fromDate, String toDate,String
List<Object[]> getTransactionresponse(String fromDate, String toDate, Long bookingId,Long hallId);
List<Object[]> getRefundResponse(String fromDate, String toDate, Long bookingId);
List<Object[]> getBookingCalendarDetails(String fromDate, String toDate, Long bookingId,String hallName);
List<BookingDetails> getBookingsByDateAndHall(String bookingDate, Long hallId);
}

454
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;
@ -135,14 +156,6 @@ public class BookingServiceImpl implements BookingService {
@Autowired
private TransRefundResRepository transRefundResRepository;
@Autowired
private QueueLogRepository queueLogRepository;
private static final Map<String, BlockingQueue<Integer>> bookingQueueMap = new ConcurrentHashMap<>();
private static final Map<String, Long> lockedSlots = new ConcurrentHashMap<>();
private static final Map<String, Timer> slotTimers = new ConcurrentHashMap<>();
@Value("${file.upload.directory}")
private String uploadDirectory;
@ -169,7 +182,7 @@ public class BookingServiceImpl implements BookingService {
}
@Override
public BookingDetails updateBookingStatus(int bookingId, BookingStatus status, String comments) {
public BookingDetails updateBookingStatus(int bookingId, BookingDetails.BookingStatus status, String comments) {
Optional<BookingDetails> booking = bookingDetailsRepository.findById(bookingId);
if (booking.isPresent()) {
BookingDetails book = booking.get();
@ -190,10 +203,12 @@ public class BookingServiceImpl implements BookingService {
}
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) {
@ -218,10 +233,6 @@ public class BookingServiceImpl implements BookingService {
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());
@ -229,10 +240,13 @@ public class BookingServiceImpl implements BookingService {
//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()) {
@ -242,8 +256,8 @@ public class BookingServiceImpl implements BookingService {
} 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()
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);
@ -269,19 +283,16 @@ public class BookingServiceImpl implements BookingService {
bookingCalendar.setEveningSlot(true);
bookingCalendar.setBookingId_2(String.valueOf(bookingId));
bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1);
}
else if (startDate.equals(endDate) && bookingDetails.getStartingSlot() == 1 && bookingDetails.getEndingSlot()==2) {
} else if (startDate.equals(endDate) && bookingDetails.getStartingSlot() == 1 && bookingDetails.getEndingSlot() == 2) {
bookingCalendar.setEveningSlot(true);
bookingCalendar.setBookingId_2(String.valueOf(bookingId));
bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1);
}
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);
}
} else if (date.equals(endDate)) {
if (bookingDetails.getEndingSlot() == 1) {
@ -298,7 +309,6 @@ public class BookingServiceImpl implements BookingService {
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);
@ -306,9 +316,9 @@ public class BookingServiceImpl implements BookingService {
bookingCalendar.setBookingId_1(String.valueOf(bookingId));
bookingCalendar.setBookingId_2(String.valueOf(bookingId));
bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 2);
bookingCalendar.setTemp_blocked(false);
}
// System.out.println(i + "end:-"+bookingCalendar.toString());
bookingCalendarRepository.save(bookingCalendar);
i++;
@ -320,7 +330,7 @@ public class BookingServiceImpl implements BookingService {
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");
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.";
@ -328,10 +338,10 @@ public class BookingServiceImpl implements BookingService {
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.";
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.getBookingDate()+"+has+been+successfully+confirmed.+%0AThanks+for+using+GCC+Community+Hall+Booking+System.";
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";
@ -388,8 +398,8 @@ public class BookingServiceImpl implements BookingService {
} 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()
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);
@ -415,8 +425,7 @@ public class BookingServiceImpl implements BookingService {
bookingCalendar.setEveningSlot(true);
bookingCalendar.setBookingId_2(String.valueOf(bookingId));
bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1);
}
else if (startDate.equals(endDate) && bookingDetails.getStartingSlot() == 1 && bookingDetails.getEndingSlot()==2) {
} else if (startDate.equals(endDate) && bookingDetails.getStartingSlot() == 1 && bookingDetails.getEndingSlot() == 2) {
bookingCalendar.setEveningSlot(true);
bookingCalendar.setBookingId_2(String.valueOf(bookingId));
bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1);
@ -455,7 +464,7 @@ public class BookingServiceImpl implements BookingService {
bookingCalendarRepository.save(bookingCalendar);
i++;
}
updateBookingStatusById(bookingDetails.getBookingId(), BookingStatus.WAITING_FOR_NOC, "Waiting for NOC Documents");
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.";
@ -485,7 +494,7 @@ public class BookingServiceImpl implements BookingService {
//System.out.println("refundedMsg=="+refundedMsg);
if (refundedMsg.equals("Refunded")) {
//System.out.println("Refund completed........");
bookingDetails.setRefundStatus(RefundStatus.COMPLETED);
bookingDetails.setRefundStatus(BookingDetails.RefundStatus.COMPLETED);
bookingDetailsRepository.save(bookingDetails);
//System.out.println("refundStatus===="+bookingDetails.getRefundStatus());
long mobile = bookingDetails.getUsers().getMobileNo();
@ -501,28 +510,18 @@ public class BookingServiceImpl implements BookingService {
// thread.start();
return "Success";
}
}
catch (Exception e){
} catch (Exception e) {
applicationLogService.saveLog(bookingDetails.getBookingId(), ApplicationLogs.logsOfMsg.ERROR.toString(), "Refund Error");
return "error";
}}
}
}
return "error";
}
@Override
public Map<String, Object> saveBookingDetails(Map<String, Object> formData) {
Map<String, Object> hs = new HashMap<>();
BookingDetails bookingDetails = null;
BookingCalendar bookingCal = new BookingCalendar();
QueueLog queueLog = new QueueLog();
Optional<BookingCalendar> existingBooking = Optional.empty();
int bcid;
// System.out.println("bc Id 2........"+formData.get("bcId"));
AtomicInteger finalBcId = new AtomicInteger();
Integer userId = userSession.getUserId();
@ -565,134 +564,9 @@ public class BookingServiceImpl implements BookingService {
String usertype = user.getUsertype().toString();
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<String> 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<Integer> 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;
@ -763,8 +637,8 @@ public class BookingServiceImpl implements BookingService {
hs.put("additionalcharges", additionalcharges);
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;
@ -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){
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");
}
// confirmation of amount
hs.put("bookingId", bookingDetails.getBookingId());
@ -919,43 +814,6 @@ 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) {
double hallAmount = 0;
if (daysrange == 1) {
@ -1053,12 +911,12 @@ 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));
@ -1069,7 +927,7 @@ public class BookingServiceImpl implements BookingService {
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
@ -1095,6 +953,7 @@ public class BookingServiceImpl implements BookingService {
public void updateBookingStatus(BookingCalendar book) {
bookingCalendarRepository.save(book);
}
public List<BookingCalendar> getCancellingdata1(String bookID) {
@ -1109,6 +968,7 @@ public class BookingServiceImpl implements BookingService {
// TODO Auto-generated method stub
return bookingDetailsRepository.findPresentsEventsByUserId(hallId);
}
public List<BookingDetails> getSettlementList(Integer hallId) {
// TODO Auto-generated method stub
return bookingDetailsRepository.getSettlementList(hallId);
@ -1125,6 +985,7 @@ public class BookingServiceImpl implements BookingService {
// TODO Auto-generated method stub
return bookingDetailsRepository.findFutureEventsByHallId(hallId);
}
@Override
public List<BookingDetails> getFilteredBookings(LocalDate fromDate, LocalDate toDate, List<Long> hallIds) {
return bookingDetailsRepository.findByFromDateBetweenAndToDateBetweenAndHallIdIn(fromDate, toDate, hallIds);
@ -1144,7 +1005,7 @@ public class BookingServiceImpl implements BookingService {
@Override
public BookingDetails updateBookingStatusById(int bookingId, BookingStatus status, String comments) {
public BookingDetails updateBookingStatusById(int bookingId, BookingDetails.BookingStatus status, String comments) {
Optional<BookingDetails> bookingDetails = bookingDetailsRepository.findById(bookingId);
if (bookingDetails.isPresent()) {
BookingDetails bookDet = bookingDetails.get();
@ -1158,7 +1019,7 @@ public class BookingServiceImpl implements BookingService {
}
@Override
public BookingDetails updateCancelledBookingStatus(int bookingId, BookingStatus status, String comments) {
public BookingDetails updateCancelledBookingStatus(int bookingId, BookingDetails.BookingStatus status, String comments) {
Optional<BookingDetails> bookingDetails = bookingDetailsRepository.findById(bookingId);
if (bookingDetails.isPresent()) {
BookingDetails bookDet = bookingDetails.get();
@ -1220,10 +1081,11 @@ public class BookingServiceImpl implements BookingService {
double startReading = ed.getStartingReading();
if (endUnit != 0) {
ed.setEndingReading(endUnit);
double usedUnit= endUnit - startReading;
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,14 +1095,14 @@ public class BookingServiceImpl implements BookingService {
}
@Override
public String cancelBooking(int bookingId, BookingStatus currentStatus,String comments) {
public String cancelBooking(int bookingId, BookingDetails.BookingStatus currentStatus, String comments) {
Optional<BookingDetails> bd = bookingDetailsRepository.findById(bookingId);
if (bd.isPresent()) {
BookingDetails bookingDetails = bd.get();
//System.out.println("currentStatus:-"+currentStatus);
if(bookingDetails.getBookingStatus().equals(BookingStatus.APPROVED)){
if (bookingDetails.getBookingStatus().equals(BookingDetails.BookingStatus.APPROVED)) {
//System.err.println("test"+currentStatus);
if(currentStatus.equals(BookingStatus.CANCELED)){
if (currentStatus.equals(BookingDetails.BookingStatus.CANCELED)) {
//System.err.println("test11"+currentStatus);
try {
//System.err.println("test13331==="+currentStatus);
@ -1248,7 +1110,7 @@ public class BookingServiceImpl implements BookingService {
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());
updateBookingStatusById(bookingDetails.getBookingId(), BookingDetails.BookingStatus.CANCELED, "user cancelled Date:-" + new Date());
List<BookingCalendar> bookingCalendarList = bookingCalendarRepository.getCancellingdata1(String.valueOf(bookingDetails.getBookingId()));
@ -1283,13 +1145,13 @@ public class BookingServiceImpl implements BookingService {
} catch (Exception e) {
e.printStackTrace();
}
} else if (currentStatus.equals(BookingStatus.REJECTED)) {
} 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);
updateBookingStatusById(bookingDetails.getBookingId(), BookingDetails.BookingStatus.REJECTED, comments);
List<BookingCalendar> bookingCalendarList = bookingCalendarRepository.getCancellingdata1(String.valueOf(bookingDetails.getBookingId()));
@ -1324,11 +1186,11 @@ public class BookingServiceImpl implements BookingService {
} catch (Exception e) {
e.printStackTrace();
}
} else if (currentStatus.equals(BookingStatus.GCC_BLOCKED)) {
} 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(), BookingStatus.GCC_BLOCKED, "total amount will refund shortly");
updateBookingStatusById(bookingDetails.getBookingId(), BookingDetails.BookingStatus.GCC_BLOCKED, "total amount will refund shortly");
} catch (Exception e) {
e.printStackTrace();
@ -1349,6 +1211,7 @@ public class BookingServiceImpl implements BookingService {
}
return null;
}
@Override
public BookingDetails saveebdetails(int bookingId, double startingReading,
MultipartFile startingReadingimage) {
@ -1375,6 +1238,7 @@ public class BookingServiceImpl implements BookingService {
}
return null;
}
@Override
public String processEbDetailsAndDamage(int bookingId, int ebId, double startingReading, double endingReading,
float usedUnit, double ebAmount, String[] assetNames, String[] comments, int[] quantities,
@ -1452,6 +1316,7 @@ public class BookingServiceImpl implements BookingService {
// TODO Auto-generated method stub
return bookingDetailsRepository.checkUserBookinglimitation(userId);
}
@Override
public List<BookingDetails> getAllBookingsByUserId(Integer userId) {
// TODO Auto-generated method stub
@ -1493,6 +1358,7 @@ public class BookingServiceImpl implements BookingService {
public List<BookingCalendar> getBookedslots(LocalDate fromDate, LocalDate endDate, List<Long> hallIdList) {
return bookingCalendarRepository.findByHallIdAndDateRange(fromDate, endDate, hallIdList);
}
// public List<String> processRefundRequests(List<String> bookingIds) {
// List<String> bookIds = new ArrayList<>();
//
@ -1664,10 +1530,12 @@ public class BookingServiceImpl implements BookingService {
public List<Object[]> getAllPaymentsDetailsByZone(String fromDate, String toDate, String zone) {
return bookingDetailsRepository.getAllPaymentsDetailsByZone(fromDate, toDate, zone);
}
@Override
public List<Object[]> getBookingHallDetailsReportByZone(String fromDate, String toDate, String zone) {
return bookingDetailsRepository.getBookingHallDetailsReportByZone(fromDate, toDate, zone);
}
//R
@Transactional
public Optional<String> updateBookingDatesAndCalendar(int bookingId, String startDat, String endDat) {
@ -1685,6 +1553,20 @@ public class BookingServiceImpl implements BookingService {
List<BookingCalendar> 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;
@ -1707,8 +1589,8 @@ public class BookingServiceImpl implements BookingService {
} 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()
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);
@ -1733,8 +1615,7 @@ public class BookingServiceImpl implements BookingService {
bookingCalendar.setEveningSlot(true);
bookingCalendar.setBookingId_2(String.valueOf(bookingId));
bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1);
}
else if (startDate.equals(endDate) && bookingDetails.getStartingSlot() == 1 && bookingDetails.getEndingSlot()==2) {
} else if (startDate.equals(endDate) && bookingDetails.getStartingSlot() == 1 && bookingDetails.getEndingSlot() == 2) {
bookingCalendar.setEveningSlot(true);
bookingCalendar.setBookingId_2(String.valueOf(bookingId));
bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1);
@ -1774,18 +1655,6 @@ public class BookingServiceImpl implements BookingService {
}
//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);
}
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";
@ -1829,7 +1698,7 @@ public class BookingServiceImpl implements BookingService {
.orElseThrow(() -> new RuntimeException("Hall not found"));
// Fetch BookingDetails with GCC_BLOCKED status
List<BookingDetails> bookingDetails = bookingDetailsRepository.findByHallDetailsAndBookingStatus(hallDetails, BookingStatus.GCC_BLOCKED);
List<BookingDetails> bookingDetails = bookingDetailsRepository.findByHallDetailsAndBookingStatus(hallDetails, BookingDetails.BookingStatus.GCC_BLOCKED);
// Fetch GccBlockingDate with BLOCKED status
List<GccBlockingDate> gccBlockingDates = gccBlockingDateRepository.findAllByHallIdAndBlockedStatus(hallId, GccBlockingDate.BlockedStatus.BLOCKED);
@ -1846,6 +1715,7 @@ public class BookingServiceImpl implements BookingService {
public int getBlockedHallCount(String blockingReason, Date startDate, Date endDate) {
return gccBlockingDateRepository.countBlockedHallsInDateRange(blockingReason, startDate, endDate);
}
public boolean isBlockingRecordExists(String fromDate, String toDate, List<Long> hallIdsList) {
LocalDate fromdate = LocalDate.parse(fromDate);
LocalDate todate = LocalDate.parse(toDate);
@ -1865,15 +1735,24 @@ public class BookingServiceImpl implements BookingService {
BookingDetails booking = optionalBooking.get();
BookingStatus currentStatus = booking.getBookingStatus();
if (currentStatus == BookingStatus.APPROVED) {
if (currentStatus == BookingStatus.APPROVED || currentStatus == BookingStatus.WAITING_FOR_NOC ||
currentStatus == BookingStatus.WAITING_FOR_NOC_APPROVAL) {
booking.setBookingStatus(BookingStatus.GCC_BLOCKED);
List<BookingCalendar> 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.setBookingId_2(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);
}
// GCC blocking entry
GccBlockingDate gcc = new GccBlockingDate();
@ -1945,19 +1824,19 @@ public class BookingServiceImpl implements BookingService {
book.setHallId(hallId.intValue());
book.setIs_active(true);
book.setIs_booked(2);
book.setIs_blocked(true);
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.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.";
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);
@ -2037,8 +1916,8 @@ public class BookingServiceImpl implements BookingService {
book.setHallId(hallId.intValue());
book.setIs_active(true);
book.setIs_booked(2);
book.setIs_blocked(true);
book.setIs_delete(false);
book.setIs_blocked(true);
updateBookingStatus(book);
}
}
@ -2195,6 +2074,7 @@ public class BookingServiceImpl implements BookingService {
// TODO Auto-generated method stub
return bookingDetailsRepository.getBookingDetailsByEventDateWithStatus(fromDate, toDate, bookingStatus, zone, division, hallid);
}
@Override
public List<Object[]> getAllPaymentsDetails(String fromDate, String toDate, String paymentStatus, String zone, String division, Integer hallid) {
// TODO Auto-generated method stub
@ -2333,17 +2213,17 @@ public class BookingServiceImpl implements BookingService {
//gccapps
@Override
public List<BookingDetails> getApprovedBookingDetails() {
return bookingDetailsRepository.findByBookingStatus(BookingStatus.APPROVED);
return bookingDetailsRepository.findByBookingStatus(BookingDetails.BookingStatus.APPROVED);
}
@Override
public List<BookingDetails> getRejectedBookingDetails() {
return bookingDetailsRepository.findByBookingStatus(BookingStatus.REJECTED);
return bookingDetailsRepository.findByBookingStatus(BookingDetails.BookingStatus.REJECTED);
}
@Override
public List<BookingDetails> getWaitingforNOCapproval() {
return bookingDetailsRepository.findByBookingStatus(BookingStatus.WAITING_FOR_NOC_APPROVAL);
return bookingDetailsRepository.findByBookingStatus(BookingDetails.BookingStatus.WAITING_FOR_NOC_APPROVAL);
}
@Override
@ -2391,14 +2271,22 @@ public class BookingServiceImpl implements BookingService {
public List<Object[]> getTransactionresponse(String fromDate, String toDate, Long bookingId, Long hallId) {
return transactionResponseRepository.getTransactionResponseByBookingId(fromDate, toDate, bookingId, hallId);
}
@Override
public List<Object[]> getRefundResponse(String fromDate, String toDate, Long bookingId) {
return transRefundResRepository.getRefundResponseByBookingId(fromDate, toDate, bookingId);
}
@Override
public List<Object[]> getBookingCalendarDetails(String fromDate, String toDate, Long bookingId, String hallName) {
return bookingCalendarRepository.findBookingCalendarDetails(fromDate, toDate, bookingId, hallName);
}
@Override
public List<BookingDetails> getBookingsByDateAndHall(String bookingDate, Long hallId) {
LocalDate date = LocalDate.parse(bookingDate); // Ensure format matches yyyy-MM-dd
return bookingDetailsRepository.findByBookingDateAndHallId(date, hallId);
}
}

2
src/main/resources/templates/admin/adminpage.html

@ -130,7 +130,7 @@
</div>
<button type="button" class="btn btn-success mb-3" onclick="addMaterialRow()"><i
class="fas fa-plus"></i>Add
</button>
Material</button>
<!-- Hidden input for total Damage Amount -->
<input type="hidden" id="hiddenTotalDamageAmount" name="totalDamageAmount">

6
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();
}

51
src/main/resources/templates/admin/gccblocking.html

@ -122,7 +122,8 @@
<h3 class="block-title"> List of Blocked Halls</h3>
<div class="block-options">
<button type="button" class="btn btn-primary" id="addButton"><i
class="far fa-plus-square"></i> Block the Halls</button>
class="far fa-plus-square"></i> Block the Halls
</button>
</div>
</div>
<div class="block-content p-0">
@ -315,7 +316,6 @@
</div>
<div class="row">
<div class="col-sm">
<label for="fromDate">From Date:</label>
@ -358,7 +358,8 @@
<!-- Button at left end corner -->
<div class="col text-left">
<button type="button" class="btn btn-primary" id="viewButton" style="margin-left:46%"
onclick="getBlockedevents()">View</button>
onclick="getBlockedevents()">View
</button>
</div>
</div>
@ -393,7 +394,8 @@
<!-- Button at left end corner -->
<div class="col text-left">
<button type="button" class="btn btn-primary" id="cancelAll"
style="margin-left:46%">Block All</button>
style="margin-left:46%">Block All
</button>
</div>
</div>
</div>
@ -635,8 +637,16 @@
var endDate = new Date(event.endDate);
var noOfDays = Math.ceil((endDate - startDate) / (1000 * 3600 * 24)) + 1;
var formattedStartDate = startDate.toLocaleDateString('en-GB', {year: 'numeric', month: '2-digit', day: '2-digit'}).replace(/\//g, '-');
var formattedEndDate = endDate.toLocaleDateString('en-GB', {year: 'numeric', month: '2-digit', day: '2-digit'}).replace(/\//g, '-');
var formattedStartDate = startDate.toLocaleDateString('en-GB', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
}).replace(/\//g, '-');
var formattedEndDate = endDate.toLocaleDateString('en-GB', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
}).replace(/\//g, '-');
var rowHtml = '<tr>' +
'<td class="text-center">' + formattedStartDate + '</td>' +
@ -651,8 +661,6 @@
});
// Booking details click handler
$(document).on('click', '.view-booking-details', function () {
var bookingId = $(this).data('booking-id');
@ -736,7 +744,7 @@
if ($(this).data('additional-value') === hallId) {
$(this).prop('checked', isChecked);
}
updateHallCheckboxes();
//updateHallCheckboxes();
updateHallDisplay();
});
});
@ -753,10 +761,11 @@
$("#selectAllCheckbox").click(function () {
var isChecked = $(this).prop('checked');
$("#bookingTableBody input[type='checkbox']").prop('checked', isChecked);
updateHallCheckboxes();
//updateHallCheckboxes();
updateHallDisplay(); // Update hall display based on selected hall IDs
});
// Event handler for the Cancel All button
$("#cancelAll").click(function () {
var fromDate = $("#fromDate").val();
var toDate = $("#toDate").val();
@ -780,13 +789,23 @@
return;
}
var allCheckboxes = $("#bookingTableBody input[type='checkbox']"); // Get all checkboxes
var selectedCheckboxes = $("#bookingTableBody input[type='checkbox']:checked"); // Get all checked checkboxes
if (allCheckboxes.length !== selectedCheckboxes.length) {
Swal.fire({
icon: "warning",
title: "Incomplete Selection",
text: "Please select all checkboxes before blocking.",
});
return; // Stop further execution
}
// Get selected checkboxes and their values and additional values
var selectedBookings = Array.from(document.querySelectorAll('#bookingTableBody input[type="checkbox"]:checked'))
.map(cb => ({
value: cb.value,
additionalValue: cb.getAttribute('data-additional-value')
}));
// Separate arrays for values and additional values
var selectedValues = selectedBookings.map(booking => booking.value);
var selectedDataHallIds = selectedBookings.map(booking => booking.additionalValue);
@ -823,6 +842,8 @@
.filter(value => !isNaN(value))
.join(',');
console.log("hallIds: "+hallIds);
// Create FormData for AJAX
var formData = new FormData();
formData.append('fromDate', fromDate);
@ -960,6 +981,7 @@
updateSelectOptions(selectedHallIds);
});
// Function to update the display of selected hall IDs
function updateHallDisplay() {
var checkedHallIds = Array.from(document.querySelectorAll('#hallSelectOptions input[type="checkbox"]:checked'))
@ -982,7 +1004,6 @@
var fromDate = $("#fromDate").val();
var toDate = $("#toDate").val();
var reasonforBlocking = $("#reasonforBlocking").val();
if (!reasonforBlocking) {
Swal.fire(
'Error!',
@ -1042,6 +1063,7 @@
}
});
}
function unblockSpecificBlockedevent(blockingId, bookingId, fromDate, hallId) {
Swal.fire({
title: 'Are you sure?',
@ -1073,6 +1095,7 @@
}
});
}
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
@ -1195,6 +1218,7 @@
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);
@ -1244,6 +1268,7 @@
});
checkboxStatusChange('hallSelectOptions', 'hallSelectLabel');
}
function checkboxStatusChange(optionsId, labelId) {
var multiselect = document.getElementById(labelId);
var multiselectOption = multiselect.getElementsByTagName('option')[0];
@ -1275,7 +1300,6 @@
}
window.onload = function () {
document.addEventListener("click", function (evt) {
var zoneFlyoutElement = document.getElementById('zoneMultiselect'),
@ -1326,6 +1350,7 @@
// 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),

6
src/main/resources/templates/admin/ongoingevents.html

@ -96,7 +96,6 @@
<th class="text-center">Action</th>-->
<th>Hall Name</th>
<th>Booking Id</th>
<th>Reason for Booking</th>
<th>Start Date</th>
<th>End Date</th>
<th>No of Days</th>
@ -122,7 +121,6 @@
</td>-->
<td th:text="${booking.hallDetails.hallName}"></td>
<td th:text="${booking.bookingId}"></td>
<td th:text="${booking.reason}"></td>
<td th:text="${booking.startDate}"></td>
<td th:text="${booking.endDate}"></td>
<td th:text="${booking.noOfDays}"></td>
@ -179,7 +177,6 @@
<th class="text-center">Action</th>-->
<th>Hall Name</th>
<th>Booking Id</th>
<th>Reason for Booking</th>
<th>Start Date</th>
<th>End Date</th>
<th>No of Days</th>
@ -206,7 +203,6 @@
<td th:text="${booking.hallDetails.hallName}"></td>
<td th:text="${booking.bookingId}"></td>
<td th:text="${booking.reason}"></td>
<td th:text="${booking.startDate}"></td>
<td th:text="${booking.endDate}"></td>
<td th:text="${booking.noOfDays}"></td>
@ -264,7 +260,6 @@
<th>Hall Name</th>
<th>Booking Id</th>
<th>Reason for Booking</th>
<th>Start Date</th>
<th>End Date</th>
<th>No of Days</th>
@ -291,7 +286,6 @@
<td th:text="${booking.hallDetails.hallName}"></td>
<td th:text="${booking.bookingId}"></td>
<td th:text="${booking.reason}"></td>
<td th:text="${booking.startDate}"></td>
<td th:text="${booking.endDate}"></td>
<td th:text="${booking.noOfDays}"></td>

3
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,
});
}
});

25
src/main/resources/templates/caretaker/caretakerpage.html

@ -130,7 +130,7 @@
</div>
<button type="button" class="btn btn-success mb-3" onclick="addMaterialRow()"><i
class="fas fa-plus"></i>Add
</button>
Material</button>
<!-- Hidden input for total Damage Amount -->
<input type="hidden" id="hiddenTotalDamageAmount" name="totalDamageAmount">
@ -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 () {

1
src/main/resources/templates/caretaker/past-booking.html

@ -101,6 +101,7 @@
<td th:text="${booking.hallDetails.hallName}"></td>
<td th:text="${booking.bookingId}"></td>
<td th:text="${booking.reason}"></td>
<td th:text="${booking.startDate}"></td>
<td th:text="${booking.endDate}"></td>
<td th:text="${booking.noOfDays}"></td>

8
src/main/resources/templates/caretaker/present-booking.html

@ -2,6 +2,8 @@
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{fragments/head-admin :: head}"></head>
</head>
<style>
.header-class {
position: fixed;
@ -275,12 +277,11 @@
</div>
<footer th:replace="~{fragments/footer2 :: footer}"></footer>
</div>
<div th:replace="~{fragments/resetpassword :: div}"></div>
<script th:replace="~{fragments/script :: script}"></script>
<script th:replace="~{fragments/loginscript :: script}"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
<script type="text/javascript">
$(document).ready(
function () {
@ -507,7 +508,6 @@
}
$(document).ready(function () {
$("#submitEbDetails").click(function () {
var bookid = parseInt($("#bookingId").val());
var startingReading = $("#startingReading").val();
@ -545,7 +545,6 @@
});
});
});
document.getElementById('EBdetailsModal').addEventListener('hide.bs.modal', function () {
// Clear the startingReading input field
document.getElementById('startingReading').value = '';
@ -553,7 +552,6 @@ document.getElementById('EBdetailsModal').addEventListener('hide.bs.modal', func
// Clear the startingReadingimage file input field
document.getElementById('startingReadingimage').value = '';
});
</script>
</body>

14
src/main/resources/templates/fragments/PaymentScript.html

@ -120,19 +120,7 @@
data: {'userId': userIdd, 'bookingId': bookingIdd},
success: function (response) {
console.log(response);
if (response.status === 'slotOccupied') {
Swal.fire({
icon: 'error',
title: 'Slot Occupied',
text: 'The selected slot is already occupied. Please choose a different slot.',
allowOutsideClick:false,
allowEscapeKey:false,
allowEnterKey:false,
confirmButtonText: 'OK'
}).then(function () {
location.reload(); // Example: reload the page
});
} else if (response.error) {
if (response.error) {
alert("please Contact Admin..")
} else {

6
src/main/resources/templates/fragments/headquartersMenu.html

@ -96,6 +96,12 @@
<span class="nav-main-link-name">Refund Failed List</span>
</a>
</li>
<li class="nav-main-item">
<a class="nav-main-link" href="/communityhall/headquarters/Gccblocking">
<i class="nav-main-link-icon fa fa-location-arrow"></i>
<span class="nav-main-link-name">Gcc Blocking</span>
</a>
</li>
<li class="nav-main-item">
<a class="nav-main-link" href="/communityhall/headquarters/Reports">
<i class="nav-main-link-icon fa fa-location-arrow"></i>

20
src/main/resources/templates/fragments/logRegiOtpScript.html

@ -17,21 +17,20 @@
document.getElementById("pds1").style.display = 'none';
document.getElementById("pds").style.display = 'block';
}
function checkLoginedIn(url, hallId) {
console.log('Hall ID being passed:', hallId); // Should print the actual hall ID value
function checkLoginedIn(url, hallId) { // Should print the actual hall ID value
if (isLogin == false) {
showloginpopup();
} else {
if (url == 'hallbookingform' || url == 'book') {
CheckBookingLimitation(function (success) {
if (success) {
if (hallId != undefined && hallId != '' && hallId !=0) {
console.log('Navigating to hallbookingform with hallId:', hallId);
window.location.href = '/communityhall/hallbookingform?hallId=' + hallId;
} else{
if (url == 'hallbookingform') {
CheckBookingLimitation(function (success) {
if (success) {
window.location.href = '/communityhall/user/' + url;
}
}
});
} else {
if (url == 'viewhistory') {
@ -39,10 +38,8 @@ function checkLoginedIn(url, hallId) {
}
}
}
}
return false;
}
// Function to show login popup and reset mobile number field
function showloginpopup() {
$('#loginModal').modal('show'); // Show the login modal
@ -626,6 +623,7 @@ function checkLoginedIn(url, hallId) {
function validateNumber() {
var mobileNo = $("#mobileno").val();
//alert("validate number.."+mobileNo);
$.ajax({
type: "GET",
url: '/communityhall/user/api/checkMobileExits',
@ -663,9 +661,9 @@ function checkLoginedIn(url, hallId) {
var mobileNo = $("#mobileNumber");
// Check if the mobile number is provided
if (!mobileNo.val()) {
// Set custom validity message
mobileNo[0].setCustomValidity("Mobile Number is Mandatory.");
if (mobileNo.val().length !== 10) {
// Set custom validity message for incorrect mobile number length
mobileNo[0].setCustomValidity("Please enter a 10-digit mobile number.");
// Report validity to trigger the validation UI
mobileNo[0].reportValidity();
return; // Exit the function to prevent the AJAX call

2
src/main/resources/templates/fragments/loginscript.html

@ -75,7 +75,7 @@
success: function(bodyMessage) {
if (bodyMessage.trim() === "Success") {
Swal.fire(
'PIN Updation!',
'PIN Registration!',
'Your New PIN Successfully Saved!<br>Now login with your new PIN.',
'success'
).then(() => {

4
src/main/resources/templates/fragments/resetpassword.html

@ -18,11 +18,11 @@
</div>
<div class="mb-4">
<label class="form-label">Old PIN<span class="text-danger">*</span></label>
<input type="password" minlength="4" maxlength="4" class="form-control text-center" name="oldpin" id="oldpin" placeholder="Numbers Only" required />
<input type="password" maxlength="4" class="form-control text-center" name="oldpin" id="oldpin" placeholder="Numbers Only" required />
</div>
<div class="mb-4">
<label class="form-label">New 4 Digit PIN <span class="text-danger">*</span></label>
<input type="password" minlength="4" maxlength="4" class="form-control text-center" name="newpin" id="newpin" placeholder="Numbers Only" required />
<input type="password" maxlength="4" class="form-control text-center" name="newpin" id="newpin" placeholder="Numbers Only" required />
</div>
</div>
<div class="block-content block-content-full text-end bg-body" id="mbutton">

10
src/main/resources/templates/headquarters/bookingwaiting.html

@ -77,7 +77,6 @@
<td class="text-center"
th:text="${booking.hallDetails.hallInchargeName} + ' / ' + ${booking.hallDetails.hallInchargeMobno}">
</td>
<td>
<p>
<span class="badge bg-warning" style="cursor: pointer;"
@ -93,7 +92,6 @@
</div>
</div>
</main>
<!-- END Main Container -->
<!--modal for pening-->
<div class="modal fade backdrop" id="pendingBookingForm" data-backdrop="static" tabindex="-1" role="dialog"
@ -323,22 +321,18 @@
<div class="modal fade" id="fileModal" tabindex="-1" role="dialog" aria-labelledby="fileModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="fileModalLabel">File Preview</h5>
<button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<embed id="filePreview" src="" width="100%" height="600px">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
@ -441,6 +435,7 @@
showReasonDocuments(list);
}
function showReasonDocuments(list) {
console.log("Reason;;;"+list.reason);
$.ajax({
type: "GET",
url: '/communityhall/api/officer/getReasonByName',
@ -448,7 +443,7 @@
'reasonName': list.reason
},
success: function (x) {
//console.log(x);
console.log("getReasonByName:.."+x);
showReasonWithDocument(x, list);
}
});
@ -702,7 +697,6 @@
responsive: true,
searching: true, // Enable search
select: false,
processing: false,
});
// Link the search input to DataTable

1387
src/main/resources/templates/headquarters/gccblocking.html
File diff suppressed because it is too large
View File

2
src/main/resources/templates/headquarters/headquarterspage.html

@ -130,7 +130,7 @@
</div>
<button type="button" class="btn btn-success mb-3" onclick="addMaterialRow()"><i
class="fas fa-plus"></i>Add
</button>
Material</button>
<!-- Hidden input for total Damage Amount -->
<input type="hidden" id="hiddenTotalDamageAmount" name="totalDamageAmount">

8
src/main/resources/templates/headquarters/ongoingevents.html

@ -97,7 +97,6 @@
<th>Hall Name</th>
<th>Booking Id</th>
<th>Reason for Booking</th>
<th>Start Date</th>
<th>End Date</th>
<th>No of Days</th>
@ -124,7 +123,6 @@
<td th:text="${booking.hallDetails.hallName}"></td>
<td th:text="${booking.bookingId}"></td>
<td th:text="${booking.reason}"></td>
<td th:text="${booking.startDate}"></td>
<td th:text="${booking.endDate}"></td>
<td th:text="${booking.noOfDays}"></td>
@ -160,7 +158,7 @@
<!-- Repeat similar structure for Cancelled Bookings Approved -->
<div class="block block-rounded">
<div class="block-header block-header-default">
<h3 class="block-title">Past Events (2 Days)</h3>
<h3 class="block-title">Past Events</h3>
</div>
<div class="block-content p-0">
<div class="p-sm-4 p-0">
@ -183,7 +181,6 @@
<th>Hall Name</th>
<th>Booking Id</th>
<th>Reason for Booking</th>
<th>Start Date</th>
<th>End Date</th>
<th>No of Days</th>
@ -210,7 +207,6 @@
<td th:text="${booking.hallDetails.hallName}"></td>
<td th:text="${booking.bookingId}"></td>
<td th:text="${booking.reason}"></td>
<td th:text="${booking.startDate}"></td>
<td th:text="${booking.endDate}"></td>
<td th:text="${booking.noOfDays}"></td>
@ -268,7 +264,6 @@
<th>Hall Name</th>
<th>Booking Id</th>
<th>Reason for Booking</th>
<th>Start Date</th>
<th>End Date</th>
<th>No of Days</th>
@ -295,7 +290,6 @@
<td th:text="${booking.hallDetails.hallName}"></td>
<td th:text="${booking.bookingId}"></td>
<td th:text="${booking.reason}"></td>
<td th:text="${booking.startDate}"></td>
<td th:text="${booking.endDate}"></td>
<td th:text="${booking.noOfDays}"></td>

3
src/main/resources/templates/headquarters/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,
});
}
});

2
src/main/resources/templates/officer/booking-list.html

@ -1,7 +1,7 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{fragments/head-admin :: head}"></head>
<head th:replace="~{fragments/head-officer :: head}"></head>
<style>
.card-body table {
width: 100%;

2
src/main/resources/templates/officer/rejected-list.html

@ -1,7 +1,7 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{fragments/head-admin :: head}"></head>
<head th:replace="~{fragments/head-officer :: head}"></head>
<style>
.card-body table {
width: 100%;

4
src/main/resources/templates/officiallogin.html

@ -162,7 +162,7 @@
</div>
<div class="mb-4">
<label class="form-label">New 4 Digit PIN <span class="text-danger">*</span></label>
<input type="password" minlength="4" maxlength="4" class="form-control text-center" name="newPinNo" id="updatedpassword" placeholder="Numbers Only" required />
<input type="password" maxlength="4" class="form-control text-center" name="newPinNo" id="updatedpassword" placeholder="Numbers Only" minlength="4" required />
</div>
</div>
<div class="block-content block-content-full text-end bg-body" id="mbutton">
@ -449,7 +449,7 @@
success: function(bodyMessage) {
if(bodyMessage.trim() == "Success"){
Swal.fire(
'PIN Updation!',
'PIN Registration!',
'Your New PIN Successfully Saved!<br>Now login with your new PIN.',
'success'
).then(() => {

620
src/main/resources/templates/user/calculatehallamount.html

@ -195,7 +195,7 @@
<select id="reasonforBooking"
name="reasonforBooking" class="form-control"
required>
<option value="">select</option>
<option value="">Select</option>
<option value="SGE">State Govt Event
</option>
<option value="CGE">Central Govt Event
@ -364,6 +364,7 @@
$(document).ready(function () {
if (hallId != null) {
getHallDetails(hallId, function (response) {
$('#hallIdDuplicate').val(hallId);
$('#selecthall').val(hallId);
$('#fullDayAmount').data('amount', response.fullDayRent);
@ -400,21 +401,26 @@
// Event listener for the Select Hall dropdown change
$('#selecthall').change(function () {
localStorage.clear();
var hallId = $(this).val();
if (hallId) {
getHallDetails(hallId, function (response) {
localStorage.setItem("isSGE",response.sge); // Fetch SGE status from the response
localStorage.setItem("isCGE",response.cge);
$('#fullDayAmount').text(response.fullDayRent.toFixed(2));
$('#halfDayAmount').text(response.halfDayRent.toFixed(2));
$('#depositAmount').text(response.depositAmount.toFixed(2));
$('#gst').text(response.gst.toFixed(0) + '%');
$('#reasonforBooking').val('');
$('#numDaysCount').val(''); // Clear the numDaysCount dropdown
$('#selectedhallId').val(hallId);
// Reset the startDate and endDate fields
$('#startPeriodDropdown').val('');
$('#endPeriodDropdown').val('');
$('#totalAmountDiv').hide();
const isSGE = response.sge; // Fetch SGE status from the response
const isCGE = response.cge;
/*if (!isSGE) {
$('#reasonforBookingdiv').hide();
}*/
@ -562,606 +568,62 @@
document.addEventListener("DOMContentLoaded", function () {
const reasonDropdown = document.getElementById("reasonforBooking");
const numDaysDropdown = document.getElementById("numDaysCount");
const startPeriodDropdown = document.getElementById("startPeriodDropdown");
const endPeriodDropdown = document.getElementById("endPeriodDropdown");
reasonDropdown.addEventListener("change", function () {
const selectedValue = reasonDropdown.value;
if (selectedValue === "MARRIAGE" || selectedValue === "COMMERCIAL") {
// Enable dropdown for Marriage and Commercial
// Enable dropdowns for Marriage and Commercial
numDaysDropdown.disabled = false;
numDaysDropdown.value = ""; // Allow the user to select
startPeriodDropdown.disabled = false;
startPeriodDropdown.value = ""; // Allow the user to select
endPeriodDropdown.disabled = false;
endPeriodDropdown.value = ""; // Allow the user to select
} else {
// Set to one day and disable for other events
numDaysDropdown.value = "1";
numDaysDropdown.disabled = true;
// Reset and disable start and end period dropdowns
startPeriodDropdown.value = "";
startPeriodDropdown.disabled = false;
endPeriodDropdown.value = "";
endPeriodDropdown.disabled = false;
}
});
});
$('#reasonforBooking').change(function () {
var isSGE = localStorage.getItem("isSGE") === "true";
var isCGE = localStorage.getItem("isCGE") === "true";
var reasonForBooking = $('#reasonforBooking').val();
</script>
</body>
</html>
<!--
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head th:replace="~{fragments/head :: head}">
<script src="https://maps.googleapis.com/maps/api/js?key="></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<style>
/* Hide button and div2 on small screens */
@media only screen and (max-width: 576px) {
/* Adjust the font size for better readability on smaller screens */
body {
font-size: 14px;
padding: 0 10px;
}
/* Modify the layout of certain elements */
.col-sm-4 {
width: 85%;
margin-bottom: 10px;
}
.select2-container {
width: 100% !important;
margin-bottom: 10px;
}
.text-center {
text-align: center !important;
}
#toggleButton {
display: none;
}
#div2 {
display: none;
}
.table-container {
overflow-y: auto;
display: flex;
justify-content: center;
align-items: center;
height: 100%;
}
.table-responsive-md {
overflow-x: auto;
-webkit-overflow-scrolling: touch;
width: 100%;
}
/* Custom CSS for table */
#amountDetails {
margin-top: 26px;
width: 95%;
if ((reasonForBooking === 'SGE' && !isSGE) || (reasonForBooking === 'CGE' && !isCGE)) {
// Show popup for Government Events
Swal.fire({
title: 'Government Event',
text: 'Shenoy Nagar Community Center (Auditorium) full Mandapam (Amma Arangam) is available for state government events.',
icon: 'info',
confirmButtonText: 'OK'
}).then((result) => {
if (result.isConfirmed) {
window.location.reload();
}
#amountDetails table {
width: 100%;
max-width: 100%;
margin: 0 auto;
border-collapse: collapse;
});
}
});
#amountDetails th,
#amountDetails td {
padding: 8px;
border: 1px solid #ddd;
text-align: left;
word-wrap: break-word;
white-space: normal;
}
/* Custom CSS for carousel */
.thumbnail {
cursor: pointer;
}
.carousel-item img {
width: 100%;
height: auto;
}
.carousel-image {
max-height: 300px;
width: auto;
margin: 0 auto;
}
</script>
.carousel-control-prev,
.carousel-control-next {
color: black;
}
/* Custom CSS for amount details */
#totalAmountDiv {
margin-top: 20px;
width: 100%;
text-align: center;
}
#totalAmount {
font-size: 18px;
font-weight: bold;
}
}
</style>
</body>
<body>
&lt;!&ndash; Pre-loader start &ndash;&gt;
<div class="theme-loader">
<div class="ball-scale">
<div class='contain'>
<div class="ring">
<div class="frame"></div>
</div>
<div class="ring">
<div class="frame"></div>
</div>
<div class="ring">
<div class="frame"></div>
</div>
<div class="ring">
<div class="frame"></div>
</div>
<div class="ring">
<div class="frame"></div>
</div>
<div class="ring">
<div class="frame"></div>
</div>
<div class="ring">
<div class="frame"></div>
</div>
<div class="ring">
<div class="frame"></div>
</div>
<div class="ring">
<div class="frame"></div>
</div>
<div class="ring">
<div class="frame"></div>
</div>
</div>
</div>
</div>
&lt;!&ndash; Pre-loader end &ndash;&gt;
<div id="pcoded" class="pcoded">
<div class="pcoded-container">
&lt;!&ndash; Menu header start &ndash;&gt;
<nav th:replace="~{fragments/nav-user :: nav}"></nav>
&lt;!&ndash; Menu header end &ndash;&gt;
<div class="pcoded-main-container">
<nav th:replace="~{fragments/nav-usermenu :: nav}"></nav>
<div class="pcoded-wrapper">
<div class="pcoded-content">
<div class="pcoded-inner-content">
&lt;!&ndash; Main-body start &ndash;&gt;
<div class="main-body">
<div class="page-wrapper">
&lt;!&ndash; Page-header start &ndash;&gt;
<div class="page-header m-t-20"></div>
&lt;!&ndash; Page-header end &ndash;&gt;
&lt;!&ndash; Page body start &ndash;&gt;
<div class="page-body">
<div class="content">
<div class="block block-rounded" style="width: 75%;margin-left: 12%;">
<div class="block-header block-header-default">
<h3 class="block-title">Calculate Rent Amount</h3>
</div>
<div class="block-content p-0">
<div class="p-sm-4 p-0">
<div class="row justify-content-center">
<div class="col-sm-4 col-lg-6 col-md-4">
<label for="selecthall">Select Hall:</label>
<select id="selecthall" class="form-control"
name="hallId" required>
<option value="">Select a hall</option>
&lt;!&ndash; Dynamically populated options will be inserted here &ndash;&gt;
</select>
</div>
<br>
<br>
<div id="amountDetails"
style="display:none; margin-top: 26px; width: 94%;">
<div class="row justify-content-center">
<div class="col-sm-4 col-lg-3 col-md-4"
style="display:none" id="reasonforBookingdiv">
<label for="reasonforBooking">Reason For
Booking:</label>
<select id="reasonforBooking"
name="reasonforBooking" class="form-control"
required>
<option value="">select</option>
<option value="SGE">State Govt Event
</option>
<option value="CGE">Central Govt Event
</option>
<option value="others">Others</option>
</select>
</div>
<div class="col-sm-4 col-lg-3 col-md-4">
<label for="numDaysCount">Number of
Days:</label>
<select class="form-control" id="numDaysCount"
name="days" required>
<option value="">Select</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
</select>
</div>
<div class="col-sm-4 col-lg-3 col-md-4"
id="startPeriodDropdowndiv"> <label
for="startPeriodDropdown">Start
Period:</label>
<select id="startPeriodDropdown"
name="startingSlot" class="form-control"
required>
<option value="">Select</option>
<option value="1">Morning (6:00 AM)</option>
<option value="2">Evening (2:00 PM)</option>
</select>
</div>
<div class="col-sm-4 col-lg-3 col-md-4"
id="endPeriodDropdowndiv"> <label
for="endPeriodDropdown">End Period:</label>
<select id="endPeriodDropdown" name="endingSlot"
class="form-control" required>
<option value="">Select</option>
<option value="1">Morning (2:00 PM)</option>
<option value="2">Evening (10:00 PM)
</option>
</select>
</div>
</div>
<br>
<div class="text-center">
<button id="calculateButton"
class="btn btn-primary">Calculate</button>
</div>
<input type="hidden" id="selectedhallId">
<div id="totalAmountDiv" class="text-center mt-3"
style="display:none;">
<table
class="table table-bordered center-table table-align">
<tbody>
<tr>
<td class="td-align"><strong> Hall
Amount:</strong>
</td>
<td><span
id="actualhallAmount_td">Rs</span>
</td>
</tr>
<tr>
<td class="td-align">
<strong>Discount:</strong>
</td>
<td><span id="discount_td">0%</span>
</td>
</tr>
<tr id="additionalcharges"
style="display:none">
<td class="td-align">
<strong>Rent Amount:</strong>
</td>
<td><span id="rentamount_td">0</span>
</td>
</tr>
<tr id="additionalcharges_tr"
style="display:none">
<td class="td-align">
<strong>Additional charges (Cleaning
+ P.A.
System + E.B):</strong>
</td>
<td><span
id="additionalcharges_td">0</span>
</td>
</tr>
<tr>
<td class="td-align"><strong>Net
Amount:</strong>
</td>
<td><span id="hallAmount_td">Rs</span>
</td>
</tr>
<tr>
<td class="td-align"><strong>GST
Amount:</strong></td>
<td><span id="gst_td">Rs</span></td>
</tr>
<tr>
<td class="td-align"><strong>Deposit
Amount:</strong></td>
<td><span
id="depositAmount_td">Rs</span>
</td>
</tr>
<tr>
<td class="td-align"><strong>Total
Amount:</strong>
</td>
<td><span id="totalAmount_td">Rs</span>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
&lt;!&ndash; Page body end &ndash;&gt;
</div>
</div>
&lt;!&ndash; Main-body end &ndash;&gt;
</div>
</div>
</div>
</div>
</div>
</div>
<footer th:replace="~{fragments/footer2 :: footer}"></footer>
&lt;!&ndash; Login Modal&ndash;&gt;
<div th:replace="~{fragments/loginreg :: div}"></div>
<script th:replace="~{fragments/script :: script}"></script>
<script th:replace="~{fragments/logRegiOtpScript :: script}"></script>
<script>
function getHallDetails(hallId, callback) {
$.ajax({
type: 'GET',
url: '/communityhall/user/api/gethalldetails/' + hallId,
success: function (response) {
callback(response);
},
error: function (xhr, status, error) {
//console.error('Error fetching hall details:', error);
}
});
}
// Get hallId from URL parameters and fetch hall details
const urlParams = new URLSearchParams(window.location.search);
const hallId = urlParams.get('hallId');
$(document).ready(function () {
if (hallId != null) {
getHallDetails(hallId, function (response) {
$('#selecthall').val(hallId);
$('#fullDayAmount').data('amount', response.fullDayRent);
$('#halfDayAmount').data('amount', response.halfDayRent);
$('#depositAmount').data('amount', response.depositAmount);
$('#gst').data('rate', response.gst);
});
}
});
// Populate the dropdown options with the received hall names
$(function () {
$("#selecthall").select2();
});
$.ajax({
type: 'GET',
url: '/communityhall/user/api/gethallnames',
success: function (response) {
var selectHallDropdown = $('#selecthall');
$.each(response, function (index, hall) {
selectHallDropdown.append($('<option></option>').attr('value', hall.hallId).text(hall.hallName));
if (hallId == hall.hallId) {
selectHallDropdown.find('option[value="' + hall.hallId + '"]').prop('selected', true);
}
});
},
error: function (xhr, status, error) {
console.error('Error fetching hall names:', error);
}
});
// Event listener for the Select Hall dropdown change
$('#selecthall').change(function () {
var hallId = $(this).val();
if (hallId) {
getHallDetails(hallId, function (response) {
$('#fullDayAmount').text(response.fullDayRent.toFixed(2));
$('#halfDayAmount').text(response.halfDayRent.toFixed(2));
$('#depositAmount').text(response.depositAmount.toFixed(2));
$('#gst').text(response.gst.toFixed(0) + '%');
$('#numDaysCount').val(''); // Clear the numDaysCount dropdown
$('#selectedhallId').val(hallId);
// Reset the startDate and endDate fields
$('#startPeriodDropdown').val('');
$('#endPeriodDropdown').val('');
$('#totalAmountDiv').hide();
const isSGE = response.sge; // Fetch SGE status from the response
const isCGE = response.cge;
if (!isSGE) {
$('#reasonforBookingdiv').hide();
} else {
$('#reasonforBookingdiv').show();
}
// Show the required amount details once hall is selected
$('#amountDetails').show();
});
} else {
// Hide the amount details if no hall is selected
$('#amountDetails').hide();
}
});
function calculateAmount(numDays, startPeriod, endPeriod, fullDayAmount, halfDayAmount) {
var amount = 0;
// If there is only one day
if (numDays === 1) {
if (startPeriod === "1" && endPeriod === "2") {
amount = fullDayAmount;
} else if (startPeriod === "1" && endPeriod === "1") {
amount = halfDayAmount;
} else if (startPeriod === "2" && endPeriod === "2") {
amount = halfDayAmount;
}
} else {
// For multiple days
if (startPeriod === "1" && endPeriod === "2") {
amount = fullDayAmount * numDays;
} else if (startPeriod === "1" && endPeriod === "1") {
amount = fullDayAmount * (numDays - 1) + halfDayAmount;
} else if (startPeriod === "2" && endPeriod === "2") {
amount = fullDayAmount * (numDays - 1) + halfDayAmount;
}
else if (startPeriod === "2" && endPeriod === "1") {
amount = fullDayAmount * (numDays - 2) + halfDayAmount * 2;
}
}
return amount;
}
function calculateGST(amount, gstRate) {
return parseFloat(((amount * gstRate) / 100).toFixed(2));
}
function handlePeriodDropdowns(numDays, startPeriod) {
if (numDays === 1 && startPeriod === "2") {
$('#endPeriodDropdown').val("2");
$('#endPeriodDropdown').prop('disabled', true);
} else {
$('#endPeriodDropdown').prop('disabled', false);
}
}
$('#numDaysCount').change(function () {
var numDays = parseInt($(this).val(), 10);
var startPeriod = $('#startPeriodDropdown').val();
handlePeriodDropdowns(numDays, startPeriod);
});
$('#startPeriodDropdown').change(function () {
var numDays = parseInt($('#numDaysCount').val(), 10);
var startPeriod = $(this).val();
handlePeriodDropdowns(numDays, startPeriod);
});
$('#calculateButton').click(function () {
var hallId = $('#selectedhallId').val();
var numDays = parseInt($('#numDaysCount').val(), 10);
var startPeriod = $('#startPeriodDropdown').val();
var endPeriod = $('#endPeriodDropdown').val();
var reasonForBooking = $('#reasonforBooking').val();
// Validate input fields
if (isNaN(numDays) || numDays < 1 || numDays > 7) {
$('#numDaysCount')[0].setCustomValidity('Please select a valid number of days.');
$('#numDaysCount')[0].reportValidity();
return;
}
if (reasonforBooking === 'SGE') {
var startPeriod = $('#startPeriodDropdown').val("1");
var endPeriod = $('#endPeriodDropdown').val("2");
}
$.ajax({
type: 'GET',
url: '/communityhall/user/api/calculatehallamount',
data: {
hallId: hallId,
numDays: numDays,
startPeriod: startPeriod,
endPeriod: endPeriod,
reasonforBooking: reasonForBooking
},
success: function (response) {
console.log(response);
// Update HTML elements with the response data
if (response.reasonforBooking === 'SGE') {
if(response.startperiod==='1' && response.endPeriod === '2'){
$('#actualhallAmount_td').text('₹' + response.fulldayhallAmount);
}else{
$('#actualhallAmount_td').text('₹' + response.halfdayhallAmount);
}
document.getElementById("additionalcharges").style.display = 'table-row'; // Show row
document.getElementById("additionalcharges_tr").style.display = 'table-row'
$('#discount_td').text(response.discount + '%');
$("#rentamount_td").html(response.rentAmount);
$("#additionalcharges_td").html('₹'+response.additionalCharges);
$('#hallAmount_td').text('₹' + response.netAmount);
$('#gst_td').text('₹' + response.gst);
$('#depositAmount_td').text('₹' + response.depositAmount);
$('#totalAmount_td').text('₹' + response.totalAmount);
$('#totalAmountDiv').show();
} else {
$('#actualhallAmount_td').text('₹' + response.amount);
$('#discount_td').text(response.discount + '%');
$('#hallAmount_td').text('₹' + response.discountAmount);
$('#gst_td').text('₹' + response.gst);
$('#depositAmount_td').text('₹' + response.depositAmount);
$('#totalAmount_td').text('₹' + response.totalAmount);
document.getElementById("additionalcharges").style.display = 'none'; // Hide row
document.getElementById("additionalcharges_tr").style.display = 'none'; // Hide row
// Show the total amount div
$('#totalAmountDiv').show();
}
},
error: function (xhr, status, error) {
console.error('Error occurred: ' + error);
}
});
});
</script>
</body>
</html>-->
</html>

16
src/main/resources/templates/user/collectionpending.html

@ -5,6 +5,7 @@
<script src="https://maps.googleapis.com/maps/api/js?key="></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<!-- Pre-loader start -->
<div class="theme-loader">
@ -121,6 +122,21 @@
class="btn btn-primary" th:onclick="|extrapaymentStart(${bookingsDetails.users.userId}, ${bookingsDetails.bookingId})|">Pay</button>
<input type="hidden" id="extrapaymentbtnSubmit"></input>
</div>
<!--<div class="text-center">
<div th:if="${bookingsDetails.settlement.collectionStatus} != 'Paid'">
<button id="calculateButton"
class="btn btn-primary"
th:onclick="|extrapaymentStart(${bookingsDetails.users.userId}, ${bookingsDetails.bookingId})|">
Pay
</button>
<input type="hidden" id="extrapaymentbtnSubmit">
</div>
<div th:if="${bookingsDetails.settlement.collectionStatus} == 'Paid'">
<button class="text-bg-danger"> Amount Paid </button>
</div>
</div>-->
</div>
</div>
</div>

5
src/main/resources/templates/user/dashboard.html

@ -507,9 +507,9 @@
th:onclick="viewHallImages([[${hall.hallId}]])">View</span></a>
</td>
<td><a
th:href="'/communityhall/hallbookingform?hallId=' + ${hall.hallId}"><span
<td><a href="javascript:void(0);"><span
class="badge bg-success"
th:onclick="return checkLoginedIn('book',[[${hall.hallId}]]);"
style="cursor: pointer;">Book</span></a>
</td>
</tr>
@ -1287,6 +1287,7 @@
}
function redirectToPage(hallId) {
alert(hallId);
window.location.href = '/communityhall/hallbookingform?hallId=' + hallId;
}

533
src/main/resources/templates/user/hallbookingform.html

@ -1,13 +1,9 @@
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml" xmlns="http://www.w3.org/1999/html">
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head th:replace="~{fragments/head :: head}"></head>
<script src="https://cdn.jsdelivr.net/npm/compressorjs@5.0.3/dist/compressor.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sockjs-client"></script>
<!--<script src="https://cdn.jsdelivr.net/npm/stompjs"></script>-->
<script src="https://cdn.jsdelivr.net/npm/stompjs@2.3.3/lib/stomp.min.js"></script>
<style>
.table-align {
width: 100%;
@ -51,29 +47,6 @@
color: #000 !important;
}
.highlight-blue .ui-state-default {
background: blue !important;
color: #FFF !important;
}
.highlight-blue a {
background-color: blue;
color: white;
}
.highlight-lightpink .ui-state-default {
background: lightpink !important;
color: #FFF !important;
}
.highlight-lightpink a,
input[type=button]:disabled {
background-color: lightpink;
color: white;
}
.btn-square-md {
width: 16px !important;
max-width: 100% !important;
@ -973,6 +946,17 @@
opacity: 0;
}
}
.highlight-blue .ui-state-default {
background: blue !important;
color: #FFF !important;
}
.highlight-blue a {
background-color: blue;
color: white;
}
</style>
<body>
@ -1142,12 +1126,6 @@
<span style="margin-left: 14px;">Gcc
Blocked</span>
</div>
<div class="col col-lg-2 col-sm-2 col-md-2">
<button type="button"
class="btn btn-primary btn-square-md"
style="background-color: lightpink"></button>
<span style="margin-left:-2px;">Temporary Blocked</span>
</div>
</div>
</div>
<br>
@ -1278,14 +1256,13 @@
Blocked</p>
</div>
<div class="col col-lg-2 col-sm-2 col-md-2">
<!--<div class="col col-lg-2 col-sm-2 col-md-2">
<button type="button"
class="btn btn-primary btn-square-md"
style="background-color: lightpink"></button>
<p style="margin-left: 6px;">Temporary
Blocked</p>
</div>
</div>-->
</div>
<br>
@ -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;">
<div>
<div class="card-body">
<div id="timer-container"
style="display: none; font-size: 20px; color: #d9534f; float:right;margin-right:10px; margin-bottom: 4px">
<span class="sand-clock"></span>Time left : <span
id="timer2">03:00</span>
</div>
<br>
<div class="col-md-12 col-sm-12 col-lg-12">
<table
class="table table-bordered table-align center-table">
@ -1517,7 +1487,7 @@
<span id="timer"
style="display: inline; float:right;margin-right:10px;">
<span class="sand-clock"></span> <!-- Hourglass icon -->
<span id="timerText">Payment Closes in 03:00</span>
<span id="timerText">Payment Closes in 01:00</span>
<!-- Timer text -->
</span>
</h6>
@ -1683,8 +1653,7 @@
<div class="col-md-12 text-center">
<!-- Center align the button -->
<button type="button" class="btn btn-primary prev-step"
style="background-color: #016d6f; color: white;"
id="previewbutton">
style="background-color: #016d6f; color: white;">
Previous
</button>
</div>
@ -1738,7 +1707,6 @@
<script th:replace="~{fragments/logRegiOtpScript :: script}"></script>
<script th:replace="~{fragments/PaymentScript :: script}"></script>
<script src="https://cdn.jsdelivr.net/npm/compressorjs@latest/dist/compressor.min.js"></script>
<!-- Payment script end-->
<script>
let reasonMaxData = new Map(); // in beginning
@ -1762,9 +1730,9 @@
$("#selecthall").val(hallId);
}
});
var countdown; // Global variable to hold the interval
var totalTime = 3 * 60; // 15 minutes in seconds
// var totalTime = 15 * 60; // 15 minutes in seconds
var totalTime = 1 * 60; // for testing
var timerElement = document.getElementById("timerText");
var confirmPaymentBtn = document.getElementById("confirmPaymentBtn");
var checkInCheckbox = document.getElementById("checkin");
@ -1797,26 +1765,6 @@
confirmPaymentBtn.disabled = true; // Disable the Confirm Payment button when time is up
checkInCheckbox.disabled = true; // Disable the Check-in checkbox when time is up
timerElement.innerHTML = "Time expired"; // Optionally update the message
// Show SweetAlert2 popup
Swal.fire({
title: 'Time Expired',
text: 'The payment window has expired. Please proceed to the next step.',
icon: 'warning',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
confirmButtonText: 'OK'
}).then((result) => {
if (result.isConfirmed) {
// Ensure that any other actions don't conflict with visibility changes
document.getElementById("previewbutton").click();
}// Redirect to step 2 when "OK" is clicked
/* window.location.href = "/communityhall/hallbookingform";! */
});
} else {
timerElement.innerHTML = "Payment Closes in " + formatTime(timeLeft);
confirmPaymentBtn.disabled = !checkInCheckbox.checked;
@ -1894,6 +1842,7 @@
return false;
}
// Function to show SweetAlert for login
function showAlertForLogin() {
Swal.fire({
@ -1998,19 +1947,9 @@
$("#endPeriodDropdown").prop("disabled", false);
var form = document.getElementById('booking');
var formData = new FormData(form);
// Retrieve bcId from localStorage if it exists
var bcid = localStorage.getItem("bcid");
console.log("bcid......." + bcid);
if (bcid) {
formData.append("bcId", bcid); // Add bcId to the FormData object
}
// Debugging: Log each FormData entry
for (var pair of formData.entries()) {
console.log(pair[0] + ', ', pair[1]);
//console.log(pair[0] + ', ', pair[1]);
}
$.ajax({
url: '/communityhall/user/api/saveTheRequest2',
@ -2019,69 +1958,18 @@
processData: false,
contentType: false,
success: function (response) {
//alert("Bc Id........"+response.bcId);
console.log("bc ID 1" + response.bcId);
console.log("response:--" + response.status);
if (response.status === 'slotOccupied') {
Swal.fire({
icon: 'error',
title: 'Slot Occupied',
text: 'The selected slot is already occupied. Please choose a different slot.',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
confirmButtonText: 'OK'
}).then(function () {
location.reload(); // Example: reload the page
});
} else if (response.status == 'slotOccupiedbyAnotherUser') {
Swal.fire({
icon: 'error',
title: 'Slot Occupied',
text: 'The selected slot is occupied by another user. Please choose a different slot.',
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
confirmButtonText: 'OK'
}).then(function () {
location.reload(); // Example: reload the page
});
} else if (response.status === 'slotLocked') {
Swal.fire({
icon: 'warning',
title: 'Slot Locked',
text: response.message,
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
confirmButtonText: 'OK'
}).then(function () {
console.log("bc ID 2" + response.bcId);
localStorage.clear();
bcid = response.bcId;
localStorage.setItem("bcid", bcid);
slotFunction();
});
} else if (response.status === 'inQueue') { /*Written for user block in queue*/
Swal.fire({
icon: 'info',
title: 'inQueue',
text: response.message,
allowOutsideClick: false,
allowEscapeKey: false,
allowEnterKey: false,
confirmButtonText: 'OK'
}).then(function () {
slotFunction();
});
// Optionally show queue position
$("#queuePosition").html("Queue Position: " + response.queuePosition);
} else {
console.log("bc ID 3" + response.bcId);
localStorage.clear();
bcid = response.bcId;
localStorage.setItem("bcid", bcid);
userId = response.userId;
bookingId = response.bookingId;
$("#bookingId").val(response.bookingId);
@ -2104,9 +1992,27 @@
}
$("#startingslot_td").html(getTimeOfDay(response.startingSlot) + " to " + getTimeOfDay(response.endingSlot));
/*$("#gst_td").html(response.gst);
$("#depositAmount_td").html(response.depositAmount);
$("#discount_td").html(response.discount + "%");
$("#actualhallAmount_td").html(response.actualhallamount);
$("#totalAmount_td").html(response.totalAmount);*/
$("#name_td").html(response.username);
$("#mobileno_td").html(response.mobileNo);
$("#usertype_td").html(response.userType);
/*if (response.reasoncode === 'SGE') {
document.getElementById("additionalcharges").style.display = 'table-row'; // Show row
document.getElementById("additionalcharges_tr").style.display = 'table-row'
$("#additionalcharges_td").html(response.additionalcharges);
$("#rentamount_td").html(0);
$("#actualhallAmount_td").html(response.actualhallamount);
$("#hallAmount_td").html(response.additionalcharges);
$("#totalAmount_td").html(response.totalAmount);
} else {
document.getElementById("additionalcharges").style.display = 'none'; // Hide row
document.getElementById("additionalcharges_tr").style.display = 'none'; // Hide row
}*/
if (response.reasoncode === 'SGE') {
document.getElementById("additionalcharges").style.display = 'table-row'; // Show row
document.getElementById("additionalcharges_tr").style.display = 'table-row'
@ -2154,66 +2060,6 @@
$("#endPeriodDropdown").prop("disabled", true);
}
function slotFunction() {
$('.step-3').show();
$('.step-4').hide();
var progressPercentage = ((3 - 1) / 3) * 100;
$(".progress-bar").css("width", progressPercentage + "%");
$('#timer-container').show();
resetQueueTimer();
}
let queueTimerInterval;
// Timer logic
function resetQueueTimer() {
//let totalTime = 15 * 60; // 15 minutes in seconds
let totalTime = 3 * 60;
const timerDisplay = document.getElementById('timer2');
const nextButton3 = document.querySelector('.step-3 .next-step');
// Enable Next button only after the timer ends
nextButton3.disabled = true;
if (queueTimerInterval) clearInterval(queueTimerInterval);
// Countdown logic
queueTimerInterval = setInterval(function () {
if (totalTime >= 0) {
const minutes = Math.floor(totalTime / 60);
const seconds = totalTime % 60;
timerDisplay.textContent = `${minutes}:${seconds.toString().padStart(2, '0')}`;
totalTime--;
} else {
clearInterval(queueTimerInterval); // Clear the interval when time is 0
nextButton3.disabled = false; // Enable the Next button
}
}, 1000);
}
// Next button click logic
document.querySelector('.step-3 .next-step').addEventListener('click', function () {
if (queueTimerInterval) clearInterval(queueTimerInterval);
if (!this.disabled) { // Only proceed if button is enabled
if ($('.step-3').is(':visible')) {
var valid = validateStep3Fields();
if (!valid) return;
$('.step-3').hide();
$('.step-4').show();
// Update progress bar for Step 4
var progressPercentage = (3 / 3) * 100;
$(".progress-bar").css("width", progressPercentage + "%");
$('#timer-container').hide();
}
}
});
function displayDocumentDetails(uploadedDocs) {
const uploadedDocsList = $("#uploadedDocsList");
@ -2447,12 +2293,34 @@
validateStep3();
});
$(".next-step").click(function () {
var valid = true;
// Validate all required text inputs and file fields in Step 3
if (currentStep === 3) {
var valid = validateStep3Fields();
if (!valid) return;
$('.step-3 input[required], .step-3 select[required]').each(function () {
if ($(this).val() === '') {
$(this).addClass('error'); // Add error class
valid = false;
return false; // Break the loop
} else {
$(this).removeClass('error'); // Remove error class if valid
}
});
$('.step-3 input[type="file"][required]').each(function () {
if ($(this)[0].files.length === 0) {
$(this).addClass('error'); // Add error class
valid = false;
return false; // Break the loop
} else {
$(this).removeClass('error'); // Remove error class if valid
}
});
}
if (!valid) {
return; // Stop if validation fails
}
if (currentStep < 4) {
@ -2582,34 +2450,15 @@
displayError(fileInput, errorMessage);
}
// Handle image files separately
if (/\.(jpg|jpeg)$/i.test(filePath) && file.size > 2097152) {
else if (/(\.jpg|\.jpeg)$/i.test(filePath) && file.size > 2097152) {
compressImage(file).then(compressedFile => {
const dataTransfer = new DataTransfer();
dataTransfer.items.add(compressedFile);
fileInput.files = dataTransfer.files;
// Validate file size after compression
validateSize(fileInput, 'greater');
validateFileSize(fileInput);
}).catch(error => {
console.error('Compression error:', error);
errorMessage = 'Error compressing image.';
displayError(fileInput, errorMessage);
});
}
// Case 2: File is a JPG/JPEG and smaller than or equal to 2MB
else if (/\.(jpg|jpeg)$/i.test(filePath) && file.size <= 2097152) {
compressImage(file).then(compressedFile => {
const dataTransfer = new DataTransfer();
dataTransfer.items.add(compressedFile);
fileInput.files = dataTransfer.files;
// Validate file size after compression
validateSize(fileInput, 'smaller');
}).catch(error => {
console.error('Compression error:', error);
errorMessage = 'Error compressing image.';
displayError(fileInput, errorMessage);
});
@ -2625,18 +2474,6 @@
}
}
function validateSize(fileInput, condition) {
const file = fileInput.files[0];
if (condition === 'greater' && file && file.size > 2097152) {
displayError(fileInput, 'File size is still greater than 2MB after compression.');
fileInput.value = ''; // Clear the file input
} else if (condition === 'smaller' && file && file.size > 2097152) {
displayError(fileInput, 'Compressed file size exceeded 2MB limit.');
fileInput.value = ''; // Clear the file input
} else {
console.log('File size is within the limit after compression.');
}
}
function isDuplicateFile(fileName, currentInput) {
const fileInputs = document.querySelectorAll('.file-upload-field');
@ -2815,7 +2652,6 @@
initializeViewerJS();
getBookingCalendar(hallId);
//connectToWebSocket(hallId);
// Set hall details in Step 2 and Step 3
$('#hallNameDisplayStep2').text(response.hallName);
@ -2906,7 +2742,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);
@ -2923,66 +2759,6 @@
});
}
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}`;
//console.log("Subscribing to topic:", topic);
stompClient.subscribe(topic, function (message) {
//console.log("Message received for hall_id:", hall_id, 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 updateEndDate() {
var startDate = new Date(document.getElementById("startDateInput").value);
@ -3253,72 +3029,135 @@
});
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 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);
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 () {
var selectedDate = $(this).val();
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();
var bookingStatus = window.bookingResponse[selectedDate];
if (bookingStatus) {
if (bookingStatus[0]) {
$("#startPeriodDropdown").val(2);
$("#startPeriodDropdown").prop("disabled", true);
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);
$("#startPeriodDropdown").prop("disabled", true);
}
} else {
$("#startPeriodDropdown").prop("disabled", false);
$("#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 [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 datepickerFormat(dateString) {
var dateObject = new Date(dateString);
var year = dateObject.getFullYear();
@ -3376,6 +3215,7 @@
$("#startDateInput")[0].setCustomValidity(""); // Clear custom validity if valid
}
});
$("#reasonforbooking").on("change", function () {
// Clear custom validity when a valid value is selected
this.setCustomValidity("");
@ -3465,39 +3305,22 @@
}
}
function validateStep3Fields() {
var valid = true;
// Confirm Payment button click event
$("#confirmPaymentBtn").on('click', function () {
// Disable the payment button
$('#confirmPaymentBtn').prop('disabled', true);
// Validate required text inputs and selects
$('.step-3 input[required], .step-3 select[required]').each(function () {
if ($(this).val() === '') {
$(this).addClass('error'); // Highlight error
valid = false;
return false; // Exit the loop
} else {
$(this).removeClass('error'); // Remove error class
}
});
stopTimer();
// Validate required file inputs
$('.step-3 input[type="file"][required]').each(function () {
if ($(this)[0].files.length === 0) {
$(this).addClass('error'); // Highlight error
valid = false;
return false;
} else {
$(this).removeClass('error'); // Remove error class
}
});
return valid;
function stopTimer() {
if (countdown) {
clearInterval(countdown);
countdown = null; // Clear the countdown reference
}
timerElement.innerHTML = "Timer Stopped"; // Optionally update the message
}
window.addEventListener("beforeunload", function () {
localStorage.removeItem("bcid"); // Clear temp block when the page unloads
});
</script>
</body>
</div>

212
src/main/resources/templates/user/viewhallform.html

@ -4,6 +4,10 @@
<head th:replace="~{fragments/head :: head}"></head>
<script src="https://cdn.jsdelivr.net/npm/compressorjs@5.0.3/dist/compressor.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sockjs-client"></script>
<!--<script src="https://cdn.jsdelivr.net/npm/stompjs"></script>-->
<script src="https://cdn.jsdelivr.net/npm/stompjs@2.3.3/lib/stomp.min.js"></script>
<style>
.table-align {
width: 100%;
@ -970,6 +974,17 @@
opacity: 0;
}
}
.highlight-blue .ui-state-default {
background: blue !important;
color: #FFF !important;
}
.highlight-blue a {
background-color: blue;
color: white;
}
</style>
<body>
@ -1127,12 +1142,12 @@
<span style="margin-left: 14px;">Gcc
Blocked</span>
</div>
<div class="col col-lg-2 col-sm-2 col-md-2">
<!--<div class="col col-lg-2 col-sm-2 col-md-2">
<button type="button"
class="btn btn-primary btn-square-md"
style="background-color: lightpink"></button>
<span style="margin-left:-2px;">Temporary Blocked</span>
</div>
</div>-->
</div>
</div>
<br>
@ -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) {

166
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;
}
@ -697,11 +673,25 @@
NOC</span>
</a>
</p>
<!--<p th:case="'noaction'">
<a class="view-button">
<span>&#45;&#45;No Action&#45;&#45;</span>
</a>
</p>-->
<p th:case="'noaction'">
<a class="view-button">
<span>--No Action--</span>
<a class="view-button"
th:if="${booking.booking_status == 'APPROVED'}">
<span class="badge bg-danger"
style="cursor: pointer;"
th:onclick="cancelBooking([[${booking.booking_id}]], [[${booking.mobile_no}]], [[${booking.booking_type}]])">Cancel
Booking</span>
</a>
</a>
</p>
<p th:case="''">
<a class="view-button">
<span>--No Action--</span>
@ -719,7 +709,8 @@
th:if="${booking.booking_status == 'APPROVED'}">
<span class="badge bg-danger"
style="cursor: pointer;"
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}]])">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</span>
</a>
</p>
@ -1300,20 +1291,22 @@
style="background-color: blue;"></button>
<p style="margin-left: 14px;">GCC Blocked</p>
</div>
<div class="col col-lg-2 col-sm-2 col-md-2">
<!--<div class="col col-lg-2 col-sm-2 col-md-2">
<button type="button" class="btn btn-primary btn-square-md"
style="background-color: lightpink;"></button>
<p style="margin-left: 14px;">Temporary Blocked</p>
</div>
</div>-->
</div>
</div>
</div>
<!-- Modal Footer -->
<div class="modal-footer">
<button type="button" class="btn btn-secondary"
data-bs-dismiss="modal">Close</button>
data-bs-dismiss="modal">Close
</button>
<button type="button" class="btn btn-primary" onclick="Reschedule()" >Save
Changes</button>
Changes
</button>
</div>
</div>
</div>
@ -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) {

Loading…
Cancel
Save