diff --git a/src/main/java/com/gcc/communityHall/controller/OfficerAPIController.java b/src/main/java/com/gcc/communityHall/controller/OfficerAPIController.java index 5480e9de..73f459b6 100644 --- a/src/main/java/com/gcc/communityHall/controller/OfficerAPIController.java +++ b/src/main/java/com/gcc/communityHall/controller/OfficerAPIController.java @@ -176,7 +176,7 @@ public class OfficerAPIController { description = "REST API for Updating the Refund Status to Approved by Settlement Id If the settlement is Approved" ) //Updating the Refund Status to Approved by Settlement Id If the settlement is Approved - @PostMapping("/updateApprovedSettlementStatus/{settlementId}") + @PostMapping("/updateApprovedSettlementStatus/{settlementId}") // need to check this API for settlement approval public ResponseEntity updateApprovedSettlementStatus( @PathVariable("settlementId") int settlementId, @RequestParam("status") BookingDetails.RefundStatus status, diff --git a/src/main/java/com/gcc/communityHall/controller/UserAPIController.java b/src/main/java/com/gcc/communityHall/controller/UserAPIController.java index 9cc89dbc..f4b27da7 100644 --- a/src/main/java/com/gcc/communityHall/controller/UserAPIController.java +++ b/src/main/java/com/gcc/communityHall/controller/UserAPIController.java @@ -1,7 +1,6 @@ package com.gcc.communityHall.controller; - import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -101,7 +100,9 @@ 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; @@ -127,129 +128,129 @@ public class UserAPIController { private AppConfig appConfig; @Autowired private UserSession userSession; - @Autowired - private SmsSenderRepository smsSenderRepository; - @Autowired - private BookingCalendarRepository bookingCalendarRepository; - @Autowired - private UserService userservice; - - @Autowired - private BookingService bookingService; - - @Autowired - private UserService userService; - - @Autowired - private CounterService counterservice; - - @Autowired - private BookingDetailsRepository bookingDetailsRepository; - - @Autowired - private BookingHistoryRepository bookingHistoryRepository; - - @Autowired - private CounterService counterService; - - @Autowired - private UserService userServices; - - @Autowired - private HallDetailService hallDetailService; - - @Autowired - private CalendarService calendarService; - - @Autowired - private UsersRepository usersRepository; - - private final String uploadDirectory; - - @Autowired - private WhatsappMsgServiceImpl whatsappMsgServiceImpl; - - @Autowired - private PaymentGatewayServiceImpl PaymentGatewayServiceImpl; - - @Autowired - private TransRefundResRepository transRefundResRepository; - - @Autowired - public UserAPIController(@Value("${file.upload.directory}") String uploadDirectory) { - this.uploadDirectory = uploadDirectory; - } - - @Operation( - summary = "Retrieving the HallDetails by HallId REST API", - description = "REST API to Retrieving the HallDetails by HallId" - ) - @ApiResponses({ - @ApiResponse( - responseCode = "200", - description = "HTTP Status UPDATED" - ), - @ApiResponse( - responseCode = "500", - description = "HTTP Status Internal Server Error", - content = @Content( - schema = @Schema(implementation = ErrorResponseDto.class) - ) - ) - } - ) - //retrieving Hall Details by HallId - @GetMapping("/gethalldetails/{hallId}") - public ResponseEntity getHallDetails(@PathVariable int hallId) { - Optional hallDetails = hallDetailsRepository.findById(hallId); - return hallDetails.map(ResponseEntity::ok) - .orElseGet(() -> ResponseEntity.status(404).body(null)); - } - - @Operation( - summary = "Retrieving the Hallnames only REST API", - description = "REST API to Retrieving the Hallnames only" - ) - - - @GetMapping("/gethallnames") - public ResponseEntity> getHallNames() { - List hallDetailsList = hallDetailsRepository.findActiveHalls(); - List hallDataList = new ArrayList<>(); - for (HallDetails hallDetails : hallDetailsList) { - HallDetails hallData = new HallDetails(); - hallData.setHallId(hallDetails.getHallId()); - hallData.setHallName(hallDetails.getHallName()); - hallDataList.add(hallData); - } - return ResponseEntity.ok(hallDataList); // Return ResponseEntity with list of HallData objects containing only id and hallname - } - - - @Operation( - summary = "Send OTP REST API", - description = "REST API For Sending OTP to user" - ) + @Autowired + private SmsSenderRepository smsSenderRepository; + @Autowired + private BookingCalendarRepository bookingCalendarRepository; + @Autowired + private UserService userservice; + + @Autowired + private BookingService bookingService; + + @Autowired + private UserService userService; + + @Autowired + private CounterService counterservice; + + @Autowired + private BookingDetailsRepository bookingDetailsRepository; + + @Autowired + private BookingHistoryRepository bookingHistoryRepository; + + @Autowired + private CounterService counterService; + + @Autowired + private UserService userServices; + + @Autowired + private HallDetailService hallDetailService; + + @Autowired + private CalendarService calendarService; + + @Autowired + private UsersRepository usersRepository; + + private final String uploadDirectory; + + @Autowired + private WhatsappMsgServiceImpl whatsappMsgServiceImpl; + + @Autowired + private PaymentGatewayServiceImpl PaymentGatewayServiceImpl; + + @Autowired + private TransRefundResRepository transRefundResRepository; + + @Autowired + public UserAPIController(@Value("${file.upload.directory}") String uploadDirectory) { + this.uploadDirectory = uploadDirectory; + } + + @Operation( + summary = "Retrieving the HallDetails by HallId REST API", + description = "REST API to Retrieving the HallDetails by HallId" + ) + @ApiResponses({ + @ApiResponse( + responseCode = "200", + description = "HTTP Status UPDATED" + ), + @ApiResponse( + responseCode = "500", + description = "HTTP Status Internal Server Error", + content = @Content( + schema = @Schema(implementation = ErrorResponseDto.class) + ) + ) + } + ) + //retrieving Hall Details by HallId + @GetMapping("/gethalldetails/{hallId}") + public ResponseEntity getHallDetails(@PathVariable int hallId) { + Optional hallDetails = hallDetailsRepository.findById(hallId); + return hallDetails.map(ResponseEntity::ok) + .orElseGet(() -> ResponseEntity.status(404).body(null)); + } + + @Operation( + summary = "Retrieving the Hallnames only REST API", + description = "REST API to Retrieving the Hallnames only" + ) + + + @GetMapping("/gethallnames") + public ResponseEntity> getHallNames() { + List hallDetailsList = hallDetailsRepository.findActiveHalls(); + List hallDataList = new ArrayList<>(); + for (HallDetails hallDetails : hallDetailsList) { + HallDetails hallData = new HallDetails(); + hallData.setHallId(hallDetails.getHallId()); + hallData.setHallName(hallDetails.getHallName()); + hallDataList.add(hallData); + } + return ResponseEntity.ok(hallDataList); // Return ResponseEntity with list of HallData objects containing only id and hallname + } + + + @Operation( + summary = "Send OTP REST API", + description = "REST API For Sending OTP to user" + ) //SendOTP @GetMapping(value = "/sendOTP") - public String sendOtp(HttpServletRequest request, @RequestParam Long mobileNo,@RequestParam String purpose) { + public String sendOtp(HttpServletRequest request, @RequestParam Long mobileNo, @RequestParam String purpose) { - Long MobileNo=mobileNo; + Long MobileNo = mobileNo; //System.out.println(purpose); //System.out.print("\n MobileNo---:"+mobileNo); Random rand = new Random(); // int otp = rand.nextInt(90000) + 10000; - int otp = 11111; - System.out.print("\n otp---:"+otp); + int otp = 11111; + System.out.print("\n otp---:" + otp); DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MMM-yyyy%20HH:mm"); LocalDateTime now = LocalDateTime.now(); //System.out.println(dtf.format(now)); - String key="pfTEYN6H"; - String generatedToken = "Welcome to GCC! Your OTP for GCC Community Centre is "+otp; - String urlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to="+mobileNo+"&from=GCCCRP&body=Welcome to GCC! Your OTP for GCC Community Centre booking is "+otp+"&entityid=1401572690000011081&templateid=1407172346444550398"; + String key = "pfTEYN6H"; + String generatedToken = "Welcome to GCC! Your OTP for GCC Community Centre is " + otp; + String urlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + mobileNo + "&from=GCCCRP&body=Welcome to GCC! Your OTP for GCC Community Centre booking is " + otp + "&entityid=1401572690000011081&templateid=1407172346444550398"; System.out.println(urlString); - System.out.println("\n urlString---: "+urlString); - String bodyMessage = ""+otp; + System.out.println("\n urlString---: " + urlString); + String bodyMessage = "" + otp; /*try { RestTemplate restTemplate = new RestTemplate(); String Response = restTemplate.getForObject(urlString, String.class); @@ -268,19 +269,18 @@ public class UserAPIController { // System.out.print("ERROR in Sending---: "+e); bodyMessage = "Error"; }*/ - HttpSession session = request.getSession(); session.setAttribute("otp", otp); return bodyMessage; } - @Operation( - summary = "Vetify OTP REST API", - description = "REST API For verifying OTP" - ) + @Operation( + summary = "Vetify OTP REST API", + description = "REST API For verifying OTP" + ) //VerifyOTP @GetMapping(value = "/verifyOTP") - public String verifyOtp(HttpServletRequest request, @RequestParam String otp,@RequestParam long mobileNo) { + public String verifyOtp(HttpServletRequest request, @RequestParam String otp, @RequestParam long mobileNo) { HttpSession session = request.getSession(); try { Integer session_otp = (Integer) session.getAttribute("otp"); @@ -290,22 +290,22 @@ public class UserAPIController { if (session_otp != null && session_otp.equals(entered_otp)) { System.out.println("Entered OTP Correct user API"); Users user = userservice.findByMobileno(mobileNo); - if(user!=null) { - userSession.setMobileno(user.getMobileNo()); - //userSession.setUserType(user.getUserType()); - userSession.setDispayName(user.getName()); - userSession.setUserId(user.getUserId()); - String userType = user.getUsertype().toString(); - userSession.setUserType(userType); + if (user != null) { + userSession.setMobileno(user.getMobileNo()); + //userSession.setUserType(user.getUserType()); + userSession.setDispayName(user.getName()); + userSession.setUserId(user.getUserId()); + String userType = user.getUsertype().toString(); + userSession.setUserType(userType); } session.setAttribute("verifiedotp", "success"); return "Success"; } else { System.out.println("Incorrect OTP. Please enter correct OTPs."); - session.setAttribute("user",""); + session.setAttribute("user", ""); session.setAttribute("mobileNo", ""); - session.setAttribute("id",""); + session.setAttribute("id", ""); session.setAttribute("verifiedotp", "error"); return "Error"; } @@ -313,146 +313,146 @@ public class UserAPIController { //System.out.println("Invalid OTP format: " + otp); return "Error"; } catch (Exception e) { - // System.out.println("Error verifying OTP: " + e.getMessage()); + // System.out.println("Error verifying OTP: " + e.getMessage()); return "Error"; } } - @GetMapping(value = "/verifyofficialOTP") - public String verifyOtp(HttpServletRequest request, @RequestParam String otp) { - HttpSession session = request.getSession(); - try { - Integer session_otp = (Integer) session.getAttribute("otp"); + + @GetMapping(value = "/verifyofficialOTP") + public String verifyOtp(HttpServletRequest request, @RequestParam String otp) { + HttpSession session = request.getSession(); + try { + Integer session_otp = (Integer) session.getAttribute("otp"); // System.out.println("session_otp---:" + session_otp); - Integer entered_otp = Integer.parseInt(otp); + Integer entered_otp = Integer.parseInt(otp); - if (session_otp != null && session_otp.equals(entered_otp)) { - //System.out.println("Entered OTP Correct"); - session.setAttribute("verifiedotp", "success"); - return "Success"; - } else { + if (session_otp != null && session_otp.equals(entered_otp)) { + //System.out.println("Entered OTP Correct"); + session.setAttribute("verifiedotp", "success"); + return "Success"; + } else { // System.out.println("Incorrect OTP. Please enter correct OTPs."); - session.setAttribute("verifiedotp", "error"); - return "Error"; - } - } catch (NumberFormatException e) { + session.setAttribute("verifiedotp", "error"); + return "Error"; + } + } catch (NumberFormatException e) { // System.out.println("Invalid OTP format: " + otp); - return "Error"; - } catch (Exception e) { - //System.out.println("Error verifying OTP: " + e.getMessage()); - return "Error"; - } - } - - @Operation( - summary = "User Mobileno Validation REST API", - description = "REST API For Validating User with Mobileno" - ) + return "Error"; + } catch (Exception e) { + //System.out.println("Error verifying OTP: " + e.getMessage()); + return "Error"; + } + } + + @Operation( + summary = "User Mobileno Validation REST API", + description = "REST API For Validating User with Mobileno" + ) //Validating User with the mobileno - @GetMapping(value = "/checkMobileExits") - public String checkMobileExits(@RequestParam long mobileno) { - try { - Users form = userservice.findByMobileno(mobileno); - if (form != null) { - return "success"; - } else { - return "error"; - } - } catch (NumberFormatException e) { - // Handle the case where the phone number cannot be parsed as a Long - return "error"; - } catch (Exception e) { - // Handle any other unexpected exceptions - return "error"; - - } - } - - @Operation( - summary = "Cousellor Mobileno Validation REST API", - description = "REST API For Validating the Counsellor Mobileno" - ) - //Counsellor Mobile no Validation - @GetMapping(value = "/checkCounsellorMobileExits") - public ResponseEntity checkCounsellorMobileExits(@RequestParam long mobileno) { - // Find the counsellor by the provided mobile number - Counsellordetails counsellor = userservice.findByMobile(mobileno); // This checks both mobileNo1 and mobileNo2 in the counsellor table - if (counsellor == null) { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Counsellor Mobile Number Not Found"); - } - - // Check if mobileNo1 or mobileNo2 of the counsellor is already used in the Users table - boolean isMobile1Used = usersRepository.existsByMobileNo(counsellor.getMobile1()); - boolean isMobile2Used = usersRepository.existsByMobileNo(counsellor.getMobile2()); - - if (isMobile1Used || isMobile2Used) { - return ResponseEntity.status(HttpStatus.CONFLICT).body("One of the counsellor's mobile numbers is already used."); - } - - // If no conflict, return success with the counsellor's name - return ResponseEntity.ok(counsellor.getName()); - } - - - - @GetMapping("/checkEmployee") - public Map checkEmployee(@RequestParam String id) { - boolean isRegistered = usersRepository.existsByGovernmentId(id); - Map response = new HashMap<>(); - response.put("isRegistered", isRegistered); - return response; - } - - - @Operation( - summary = "Retriving the zone REST API", - description = "REST API to Retriev the zone for displaying in Frontend" - ) - //retrieving the zone - @GetMapping(value = "/getZone") - public List> getZone() { - return hallDetailsRepository.getZoneAndDivision(); - } - - @Operation( - summary = "Zones by Hall REST API", - description = "REST API to Retrieve the zone by Hall for displaying in GccBlocking page" - ) - //retrieving the zones by hall - @GetMapping(value = "/hallsbyzone") - public List> getHallsByZone(@RequestParam(required = false) String zones) { - if (zones == null || zones.isEmpty()) { - return hallDetailsRepository.getAllHalls(); - } else { - List zoneList = Arrays.asList(zones.split(",")); - return hallDetailsRepository.getHallsByZones(zoneList); - } - } - - @Operation( - summary = "Past Data from the booking Calendar Hall REST API", - description = "REST API to Retrieve the Pat Data from booking calendar" - ) - //Getting the Past Data from the Calendar - @GetMapping("/getPastData") - public List getPastData(@RequestParam("hall_id") int hall_id){ - List data = new ArrayList(); - data = bookingService.getPastData(hall_id); - if(data!=null) { - return data; - } - return data; - } - - @Operation( - summary = "Pensioner Details ERP REST API", - description = "REST API to retrieving the Pensioner Details From ERP" - ) - //retrieving the Pensioner Details From ERP - @GetMapping("/PensionerDetail") - public PensionerDetailsResponse getPensionerDetails(@RequestParam("pensionerId") String pensionerId) { - //System.out.println(pensionerId); - RestTemplate restTemplate = new RestTemplate(); - String url = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?serviceId=getPensionerDetailsList&pensionerId="+pensionerId; + @GetMapping(value = "/checkMobileExits") + public String checkMobileExits(@RequestParam long mobileno) { + try { + Users form = userservice.findByMobileno(mobileno); + if (form != null) { + return "success"; + } else { + return "error"; + } + } catch (NumberFormatException e) { + // Handle the case where the phone number cannot be parsed as a Long + return "error"; + } catch (Exception e) { + // Handle any other unexpected exceptions + return "error"; + + } + } + + @Operation( + summary = "Cousellor Mobileno Validation REST API", + description = "REST API For Validating the Counsellor Mobileno" + ) + //Counsellor Mobile no Validation + @GetMapping(value = "/checkCounsellorMobileExits") + public ResponseEntity checkCounsellorMobileExits(@RequestParam long mobileno) { + // Find the counsellor by the provided mobile number + Counsellordetails counsellor = userservice.findByMobile(mobileno); // This checks both mobileNo1 and mobileNo2 in the counsellor table + if (counsellor == null) { + return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Counsellor Mobile Number Not Found"); + } + + // Check if mobileNo1 or mobileNo2 of the counsellor is already used in the Users table + boolean isMobile1Used = usersRepository.existsByMobileNo(counsellor.getMobile1()); + boolean isMobile2Used = usersRepository.existsByMobileNo(counsellor.getMobile2()); + + if (isMobile1Used || isMobile2Used) { + return ResponseEntity.status(HttpStatus.CONFLICT).body("One of the counsellor's mobile numbers is already used."); + } + + // If no conflict, return success with the counsellor's name + return ResponseEntity.ok(counsellor.getName()); + } + + + @GetMapping("/checkEmployee") + public Map checkEmployee(@RequestParam String id) { + boolean isRegistered = usersRepository.existsByGovernmentId(id); + Map response = new HashMap<>(); + response.put("isRegistered", isRegistered); + return response; + } + + + @Operation( + summary = "Retriving the zone REST API", + description = "REST API to Retriev the zone for displaying in Frontend" + ) + //retrieving the zone + @GetMapping(value = "/getZone") + public List> getZone() { + return hallDetailsRepository.getZoneAndDivision(); + } + + @Operation( + summary = "Zones by Hall REST API", + description = "REST API to Retrieve the zone by Hall for displaying in GccBlocking page" + ) + //retrieving the zones by hall + @GetMapping(value = "/hallsbyzone") + public List> getHallsByZone(@RequestParam(required = false) String zones) { + if (zones == null || zones.isEmpty()) { + return hallDetailsRepository.getAllHalls(); + } else { + List zoneList = Arrays.asList(zones.split(",")); + return hallDetailsRepository.getHallsByZones(zoneList); + } + } + + @Operation( + summary = "Past Data from the booking Calendar Hall REST API", + description = "REST API to Retrieve the Pat Data from booking calendar" + ) + //Getting the Past Data from the Calendar + @GetMapping("/getPastData") + public List getPastData(@RequestParam("hall_id") int hall_id) { + List data = new ArrayList(); + data = bookingService.getPastData(hall_id); + if (data != null) { + return data; + } + return data; + } + + @Operation( + summary = "Pensioner Details ERP REST API", + description = "REST API to retrieving the Pensioner Details From ERP" + ) + //retrieving the Pensioner Details From ERP + @GetMapping("/PensionerDetail") + public PensionerDetailsResponse getPensionerDetails(@RequestParam("pensionerId") String pensionerId) { + //System.out.println(pensionerId); + RestTemplate restTemplate = new RestTemplate(); + String url = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?serviceId=getPensionerDetailsList&pensionerId=" + pensionerId; ResponseEntity responseEntity = restTemplate.getForEntity(url, String.class); @@ -463,7 +463,7 @@ public class UserAPIController { // Extract the Java object from the response body ObjectMapper objectMapper = new ObjectMapper(); try { - PensionerDetailsResponse pensionerResponse = objectMapper.readValue(jsonString, PensionerDetailsResponse.class); + PensionerDetailsResponse pensionerResponse = objectMapper.readValue(jsonString, PensionerDetailsResponse.class); // Now you can access the pensionerResponse object as usual // e.g., pensionerResponse.getPensioners() to get the list of pensioners @@ -476,17 +476,17 @@ public class UserAPIController { } //return null; - } - - @Operation( - summary = "Employee Details ERP REST API", - description = "REST API to retrieving the Employee Details From ERP" - ) - @GetMapping("/EmployeeDetails") - public EmployeeDetailsResponse getEmployeeDetails(@RequestParam("employeeId") Long employeeId) { - //System.out.println("Employee ID:"+employeeId); - RestTemplate restTemplate = new RestTemplate(); - String url = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?serviceId=getEmployeeDetail&EmployeeID="+employeeId; + } + + @Operation( + summary = "Employee Details ERP REST API", + description = "REST API to retrieving the Employee Details From ERP" + ) + @GetMapping("/EmployeeDetails") + public EmployeeDetailsResponse getEmployeeDetails(@RequestParam("employeeId") Long employeeId) { + //System.out.println("Employee ID:"+employeeId); + RestTemplate restTemplate = new RestTemplate(); + String url = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?serviceId=getEmployeeDetail&EmployeeID=" + employeeId; ResponseEntity responseEntity = restTemplate.getForEntity(url, String.class); @@ -510,17 +510,17 @@ public class UserAPIController { } //return null; - } + } - @Operation( - summary = "FamilyPensioner Details ERP REST API", - description = "REST API to retrieving the FamilyPensioner Details From ERP" - ) - //retrieving the FamilyPensionerDetails Details From ERP - @GetMapping("/FamilyPensionerDetail") - public FamilyPensionerDetailsResponse getFamilyPensionerDetails(@RequestParam("id") Long id) { - RestTemplate restTemplate = new RestTemplate(); - String url = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?serviceId=getFamPensionerDetailsList&familPensionId="+id; + @Operation( + summary = "FamilyPensioner Details ERP REST API", + description = "REST API to retrieving the FamilyPensioner Details From ERP" + ) + //retrieving the FamilyPensionerDetails Details From ERP + @GetMapping("/FamilyPensionerDetail") + public FamilyPensionerDetailsResponse getFamilyPensionerDetails(@RequestParam("id") Long id) { + RestTemplate restTemplate = new RestTemplate(); + String url = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?serviceId=getFamPensionerDetailsList&familPensionId=" + id; ResponseEntity responseEntity = restTemplate.getForEntity(url, String.class); @@ -542,14 +542,14 @@ public class UserAPIController { e.printStackTrace(); return null; } - } - - @Operation( - summary = "Hall Details coordinates REST API", - description = "REST API to retrieving the Hall Details coordinates for Map" - ) - //retrieving the All Hall Details coordinates - @GetMapping("/getallhallcoordinates") + } + + @Operation( + summary = "Hall Details coordinates REST API", + description = "REST API to retrieving the Hall Details coordinates for Map" + ) + //retrieving the All Hall Details coordinates + @GetMapping("/getallhallcoordinates") public List> getAllHallCoordinates() { List allHallDetails = hallDetailsRepository.findActiveHalls(); return allHallDetails.stream().map(this::extractRequiredDetails).collect(Collectors.toList()); @@ -557,12 +557,12 @@ public class UserAPIController { private Map extractRequiredDetails(HallDetails hallDetails) { Map details = new HashMap<>(); - + details.put("latitude", hallDetails.getLatitude()); details.put("longitude", hallDetails.getLongitude()); details.put("hallId", String.valueOf(hallDetails.getHallId())); details.put("hallName", hallDetails.getHallName()); - details.put("seatingCapacity",String.valueOf(hallDetails.getSeatingCapacity()) ); + details.put("seatingCapacity", String.valueOf(hallDetails.getSeatingCapacity())); details.put("parkingCapacity", hallDetails.getParkingCapacity()); details.put("hallImage", hallDetails.getHallImagesList()); details.put("fullDayRent", hallDetails.getFullDayRent()); @@ -571,26 +571,26 @@ public class UserAPIController { details.put("area", hallDetails.getArea()); details.put("street", hallDetails.getStreet()); details.put("landMark", hallDetails.getLandMark()); - details.put("doorNo", hallDetails.getDoorNo()); - details.put("hallArea", hallDetails.getHallArea()); + details.put("doorNo", hallDetails.getDoorNo()); + details.put("hallArea", hallDetails.getHallArea()); return details; } - + @Operation( summary = "Booking Limitation Details ERP REST API", description = "REST API to check the Booking Limitation & UserStatus pending" ) - //Booking Limitation & UserStatus pending + //Booking Limitation & UserStatus pending @GetMapping("/bookingLimit") public String CheckbookingLimitation(Model model) { - int userId = userSession.getUserId(); - Users userById = userService.getUserById(userId); - if(userById!=null && userById.getUserstatus()==Users.userStatus.PENDING) { - return "pending"; - } - if (userById != null && userById.getUserstatus() == Users.userStatus.REJECTED) { - return "rejected"; - } + int userId = userSession.getUserId(); + Users userById = userService.getUserById(userId); + if (userById != null && userById.getUserstatus() == Users.userStatus.PENDING) { + return "pending"; + } + if (userById != null && userById.getUserstatus() == Users.userStatus.REJECTED) { + return "rejected"; + } int checkUserBookingLimitation = bookingService.checkUserBookinglimitation(userId); // System.out.println("checkUserBookingLimitation="+checkUserBookingLimitation); if (checkUserBookingLimitation < 2) { @@ -599,7 +599,7 @@ public class UserAPIController { } return "failure"; } - + @Operation( summary = "Counter Booikng Limit REST API", description = "REST API to check the Counter Booking Limitation" @@ -609,20 +609,20 @@ public class UserAPIController { Users user = userService.getUserDetailsByMobileNo(mobileNo); if (user == null) { - // System.err.println("User not found for mobile number: " + mobileNo); + // System.err.println("User not found for mobile number: " + mobileNo); return "checkmobilenoexists"; // You can return a different status or handle it accordingly } int userId = user.getUserId(); int checkUserBookingLimitation = bookingService.checkUserBookinglimitation(userId); - + if (checkUserBookingLimitation >= 2) { - // System.err.println("bookinglimitreached"); + // System.err.println("bookinglimitreached"); return "bookinglimitreached"; } if (user != null && !user.isActive()) { return "deactive"; } - + return "checkmobilenoexists"; } @@ -654,15 +654,15 @@ public class UserAPIController { userDetails.put("displayName", userSession.getDispayName()); userDetails.put("mobileNo", userSession.getMobileno()); userDetails.put("userType", userSession.getUserType()); - + return ResponseEntity.ok(userDetails); } - + @GetMapping(value = "/getZonehalls") public List> getZonehalls() { return hallDetailsRepository.getZonesAndDivisions(); } - + @Operation( summary = "ZONES from ERP REST API", description = "REST API to get the zones from ERP" @@ -671,7 +671,7 @@ public class UserAPIController { @GetMapping(value = "/getZoneNo") public String getZoneNo() { - String urlString = appConfig.getErpUrl()+"serviceId=getZones"; + String urlString = appConfig.getErpUrl() + "serviceId=getZones"; ResponseEntity response = null; RestTemplate restTemplate = new RestTemplate(); String bodyMessage = ""; @@ -696,7 +696,7 @@ public class UserAPIController { // Rest Api From ERP for getting Divisions @GetMapping(value = "/getDiv") public String getDiv(@RequestParam String zoneId) { - String urlString = appConfig.getErpUrl()+"serviceId=getWards&Zoneid="+zoneId+""; + String urlString = appConfig.getErpUrl() + "serviceId=getWards&Zoneid=" + zoneId + ""; ResponseEntity response = null; RestTemplate restTemplate = new RestTemplate(); String bodyMessage = ""; @@ -714,7 +714,7 @@ public class UserAPIController { } return bodyMessage; } - + @Operation( summary = "HAlls By Division ERP REST API", description = "REST API to get the HAlls by Divisions" @@ -724,7 +724,7 @@ public class UserAPIController { public List getHallsByDivision(@RequestParam("division") String division) { return hallDetailsRepository.findByDivision(division); } - + @Operation( summary = "HAlls By zone ERP REST API", description = "REST API to get the HAlls by zone" @@ -733,7 +733,7 @@ public class UserAPIController { public List getHallsByzone(@RequestParam("zone") String zone) { return hallDetailsRepository.findByZone(zone); } - + @Operation( summary = "Booking Details By bookingId ERP REST API", description = "REST API to get the Booking Details based on BookingId" @@ -741,29 +741,46 @@ public class UserAPIController { //retrieving the Booking Details based on BookingId @GetMapping("/viewAllBookingDetails") public ResponseEntity getUserDetailsByBookingId(@RequestParam("bookingId") int bookingId) { + + LocalDateTime rescheduledUpdatedDate = null; + BookingDetails bookingDetails = bookingService.getBookingsById(bookingId); + if (bookingDetails.getComments().equals( "slots Resheduled the Dates")) { + rescheduledUpdatedDate = LocalDateTime.parse(bookingDetails.getUpdatedDate()); + } /*else if(bookingDetails.getScheduleCount()==1){ + List histories = bookingDetails.getBookingHistories(); + + if (histories != null && !histories.isEmpty()) { + rescheduledUpdatedDate = histories.stream() + .filter(history -> "slots Resheduled the Dates".equals(history.getComments())) + .map(BookingHistory::getUpdatedDate) + .findFirst() + .orElse(null); } + + }*/ + if (bookingDetails != null) { return ResponseEntity.ok(bookingDetails); } else { return ResponseEntity.notFound().build(); } } - + @Operation( summary = "New Registration in Counter REST API", description = "REST API for New Registration in Counter" ) - //New Registration in Counter + //New Registration in Counter @PostMapping("/newcounterregistrationform") public ResponseEntity showRegistrationForm( @ModelAttribute Users counterform, @RequestParam(value = "userPhoto", required = false) MultipartFile userPhoto) { - + try { if (userPhoto != null && !userPhoto.isEmpty()) { counterform.setUserPhoto(userPhoto); // Set the photo if it exists } - + Users user = userService.user(counterform); userSession.setMobileno(user.getMobileNo()); userSession.setDispayName(user.getName()); @@ -786,114 +803,114 @@ public class UserAPIController { } } - + @Operation( summary = "Counter User Details REST API", description = "REST API to get the User Details by Mobileno for counter" ) - //retrieving the User Details by Mobileno for Counter - @GetMapping("/getUserDetails") - public ResponseEntity getUserDetailsByMobileNo(@RequestParam("mobileNo") long mobileNo) { - try { - // Call service method to retrieve user details by mobile number - Users userDetails = userService.getUserDetailsByMobileNo(mobileNo); - if (userDetails != null) { - return ResponseEntity.ok(userDetails); - } else { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("User not found"); - } - } catch (Exception e) { - // Log the exception and return an appropriate error response - e.printStackTrace(); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error retrieving user details"); - } - } - + //retrieving the User Details by Mobileno for Counter + @GetMapping("/getUserDetails") + public ResponseEntity getUserDetailsByMobileNo(@RequestParam("mobileNo") long mobileNo) { + try { + // Call service method to retrieve user details by mobile number + Users userDetails = userService.getUserDetailsByMobileNo(mobileNo); + if (userDetails != null) { + return ResponseEntity.ok(userDetails); + } else { + return ResponseEntity.status(HttpStatus.NOT_FOUND).body("User not found"); + } + } catch (Exception e) { + // Log the exception and return an appropriate error response + e.printStackTrace(); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error retrieving user details"); + } + } + @Operation( summary = "DD Image by CounterID REST API", description = "REST API to get the DD Image by counterId" ) - //retrieving the Dd Image by counterId - @GetMapping("/getImageByDdId") - public ResponseEntity getImageByDdId(@RequestParam int counterId) { - CounterDetails counterDetails = counterservice.getDdImageById(counterId); - if (counterDetails != null) { - //System.out.println("CounterDetails found: " + counterDetails.getDdphoto()); - return ResponseEntity.ok(counterDetails); - } else { - //System.out.println("CounterDetails not found for ID: " + counterId); - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); - } - } - + //retrieving the Dd Image by counterId + @GetMapping("/getImageByDdId") + public ResponseEntity getImageByDdId(@RequestParam int counterId) { + CounterDetails counterDetails = counterservice.getDdImageById(counterId); + if (counterDetails != null) { + //System.out.println("CounterDetails found: " + counterDetails.getDdphoto()); + return ResponseEntity.ok(counterDetails); + } else { + //System.out.println("CounterDetails not found for ID: " + counterId); + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); + } + } + @Operation( summary = "Counter Booking Cancellation by Letter and Reason REST API", description = "REST API save the counter Booking Cancellation Letter and reason" ) - //Saving the counter Booking Cancellation Letter and reason - @PostMapping("/saveCancellation") - public ResponseEntity saveCancellation( - @RequestParam("counterId") int counterId, - @RequestParam("uploadLetter") MultipartFile uploadLetter, - @RequestParam("reason") String reason) throws IOException { - - //System.out.println("Received counterId: " + counterId); - //System.out.println("Received file: " + uploadLetter.getOriginalFilename()); - - // Fetch booking details using counterId - List bookingList = bookingDetailsRepository.findByCounterId(counterId); - - if (bookingList.isEmpty()) { - //System.out.println("No bookings found for counterId: " + counterId); - } - - for (BookingDetails booking : bookingList) { - booking.setBookingStatus(BookingStatus.CANCELED); - bookingDetailsRepository.save(booking); - - List bookingCalendarList = bookingCalendarRepository.getCancellingdata1(String.valueOf(booking.getBookingId())); - - for (BookingCalendar calendar : bookingCalendarList) { - boolean isUpdated = false; - - if (String.valueOf(booking.getBookingId()).equals(calendar.getBookingId_1())) { - calendar.setBookingId_1(null); - isUpdated = true; - } - if (String.valueOf(booking.getBookingId()).equals(calendar.getBookingId_2())) { - calendar.setBookingId_2(null); - isUpdated = true; - } - if (calendar.isMorningSlot()) { - calendar.setMorningSlot(false); - isUpdated = true; - } - if (calendar.isEveningSlot()) { - calendar.setEveningSlot(false); - isUpdated = true; - } - if (isUpdated) { - calendar.setIs_delete(true); - bookingCalendarRepository.save(calendar); - } - } - } - CounterRefundList counterRefundList = counterservice.saveCancellation(counterId, uploadLetter, reason); - - return ResponseEntity.ok(counterRefundList); - } + //Saving the counter Booking Cancellation Letter and reason + @PostMapping("/saveCancellation") + public ResponseEntity saveCancellation( + @RequestParam("counterId") int counterId, + @RequestParam("uploadLetter") MultipartFile uploadLetter, + @RequestParam("reason") String reason) throws IOException { + + //System.out.println("Received counterId: " + counterId); + //System.out.println("Received file: " + uploadLetter.getOriginalFilename()); + + // Fetch booking details using counterId + List bookingList = bookingDetailsRepository.findByCounterId(counterId); + + if (bookingList.isEmpty()) { + //System.out.println("No bookings found for counterId: " + counterId); + } + + for (BookingDetails booking : bookingList) { + booking.setBookingStatus(BookingStatus.CANCELED); + bookingDetailsRepository.save(booking); + + List bookingCalendarList = bookingCalendarRepository.getCancellingdata1(String.valueOf(booking.getBookingId())); + + for (BookingCalendar calendar : bookingCalendarList) { + boolean isUpdated = false; + + if (String.valueOf(booking.getBookingId()).equals(calendar.getBookingId_1())) { + calendar.setBookingId_1(null); + isUpdated = true; + } + if (String.valueOf(booking.getBookingId()).equals(calendar.getBookingId_2())) { + calendar.setBookingId_2(null); + isUpdated = true; + } + if (calendar.isMorningSlot()) { + calendar.setMorningSlot(false); + isUpdated = true; + } + if (calendar.isEveningSlot()) { + calendar.setEveningSlot(false); + isUpdated = true; + } + if (isUpdated) { + calendar.setIs_delete(true); + bookingCalendarRepository.save(calendar); + } + } + } + CounterRefundList counterRefundList = counterservice.saveCancellation(counterId, uploadLetter, reason); + + return ResponseEntity.ok(counterRefundList); + } @Operation( summary = "Counter Booking Details by CounterId REST API", description = "REST API to get the Counter Details by CounterId" ) - //retrieving Counter Booking Details by counterId - @GetMapping("/counterdetails") - public List getUserDetailsbycounterId(@RequestParam("counterId") int counterId) { - List counterRefundList = bookingDetailsRepository.getCounterDetailsbycounterId(counterId); - return counterRefundList; - } + //retrieving Counter Booking Details by counterId + @GetMapping("/counterdetails") + public List getUserDetailsbycounterId(@RequestParam("counterId") int counterId) { + List counterRefundList = bookingDetailsRepository.getCounterDetailsbycounterId(counterId); + return counterRefundList; + } // @GetMapping("/getUser") @@ -903,12 +920,12 @@ public class UserAPIController { // } // return ResponseEntity.ok(userService.getUserById(userId)); // } - + @Operation( summary = "Updating the User Details Mobileno Validation REST API", description = "REST API to Update the User Details if the User status is Rejected" ) - //Updating the Rejected user details + //Updating the Rejected user details @PostMapping("/updateUserDetails") public String updateUserDetails( @RequestParam("userId") int userId, @@ -917,8 +934,8 @@ public class UserAPIController { @RequestParam(value = "area", required = false) String area, @RequestParam(value = "location", required = false) String location, @RequestParam(value = "usertype", required = false) String userType, - @RequestParam(value="pinCode", required = false) int pinCode, - @RequestParam(value="email", required = false) String email, + @RequestParam(value = "pinCode", required = false) int pinCode, + @RequestParam(value = "email", required = false) String email, @RequestParam(value = "profilephoto", required = false) MultipartFile profilephoto) { Users userDetails = new Users(); @@ -962,618 +979,612 @@ public class UserAPIController { return userServices.updateUserDetails(userDetails); } - + @Operation( summary = "Counter User Details REST API", description = "REST API to Get the User Details for Counter" ) - //Retrive user details for counter - @GetMapping("/getuserforcounter") - public ResponseEntity getCounterUserById(@RequestParam int userId){ - if(userId == 0) { - userId = userSession.getUserId(); - // System.out.println("User ID retrieved from session: " + userId); - } else { - //System.out.println("User ID provided as parameter: " + userId); - } + //Retrive user details for counter + @GetMapping("/getuserforcounter") + public ResponseEntity getCounterUserById(@RequestParam int userId) { + if (userId == 0) { + userId = userSession.getUserId(); + // System.out.println("User ID retrieved from session: " + userId); + } else { + //System.out.println("User ID provided as parameter: " + userId); + } - Users user = userService.getUserById(userId); - if(user == null) { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("User not found"); - } - return ResponseEntity.ok(user); - } + Users user = userService.getUserById(userId); + if (user == null) { + return ResponseEntity.status(HttpStatus.NOT_FOUND).body("User not found"); + } + return ResponseEntity.ok(user); + } @Operation( summary = "User Details REST API", description = "REST API to Get the User Details" ) - //retrieving User Details - @GetMapping("/getUser") - public ResponseEntity getUserByID(@RequestParam int userId) { - if (userId == 0) { - userId = userSession.getUserId(); - } - Users user = userService.getUserById(userId); - Map response = new HashMap<>(); - response.put("userId",user.getUserId()); - response.put("name", user.getName()); - response.put("email", user.getEmail()); - response.put("mobileNo", user.getMobileNo()); - response.put("doorNo", user.getDoorNo()); - response.put("area", user.getArea()); - response.put("location", user.getLocation()); - response.put("pinCode", user.getPinCode()); - response.put("userstatus", user.getUserstatus()); - response.put("profilephoto", user.getProfilephoto()); - response.put("usertype", user.getUsertype()); - - if ("REJECTED".equalsIgnoreCase(user.getUserstatus().name())) { - List histories = user.getUserHistories(); - String rejectionReason = histories.stream() - .filter(history -> history.getComments() != null) - .map(UserHistory::getComments) - .findFirst() - .orElse("No reason provided"); - response.put("rejectionReason", rejectionReason); - } + //retrieving User Details + @GetMapping("/getUser") + public ResponseEntity getUserByID(@RequestParam int userId) { + if (userId == 0) { + userId = userSession.getUserId(); + } + Users user = userService.getUserById(userId); + Map response = new HashMap<>(); + response.put("userId", user.getUserId()); + response.put("name", user.getName()); + response.put("email", user.getEmail()); + response.put("mobileNo", user.getMobileNo()); + response.put("doorNo", user.getDoorNo()); + response.put("area", user.getArea()); + response.put("location", user.getLocation()); + response.put("pinCode", user.getPinCode()); + response.put("userstatus", user.getUserstatus()); + response.put("profilephoto", user.getProfilephoto()); + response.put("usertype", user.getUsertype()); + + if ("REJECTED".equalsIgnoreCase(user.getUserstatus().name())) { + List histories = user.getUserHistories(); + String rejectionReason = histories.stream() + .filter(history -> history.getComments() != null) + .map(UserHistory::getComments) + .findFirst() + .orElse("No reason provided"); + response.put("rejectionReason", rejectionReason); + } - //System.out.println("Response: " + response); // Log the response - return ResponseEntity.ok(response); - } + //System.out.println("Response: " + response); // Log the response + return ResponseEntity.ok(response); + } @Operation( summary = "Saving the Booking Details REST API", description = "REST API to Save the Booking Details" ) - //APi for Saving the Booking Details - @PostMapping(path = "/saveTheRequest2", consumes = { "multipart/form-data" }) - public ResponseEntity saveTheBookingDetails2(HttpServletRequest request) { - MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; - Map bookingDetails = splitFormData(multipartRequest); - Map saveBookingDetails = bookingService.saveBookingDetails(bookingDetails); - return ResponseEntity.ok(saveBookingDetails); - } - - public Map splitFormData(MultipartHttpServletRequest multipartRequest){ - Map formData = new HashMap<>(); - - // Iterate through the request parameters - Enumeration parameterNames = multipartRequest.getParameterNames(); - while (parameterNames.hasMoreElements()) { - String paramName = parameterNames.nextElement(); - String paramValues = multipartRequest.getParameter(paramName); - formData.put(paramName, paramValues); - } + //APi for Saving the Booking Details + @PostMapping(path = "/saveTheRequest2", consumes = {"multipart/form-data"}) + public ResponseEntity saveTheBookingDetails2(HttpServletRequest request) { + MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; + Map bookingDetails = splitFormData(multipartRequest); + Map saveBookingDetails = bookingService.saveBookingDetails(bookingDetails); + return ResponseEntity.ok(saveBookingDetails); + } - // Iterate through the request parts (files) - try { - Map fileMap = multipartRequest.getFileMap(); - for (Map.Entry entry : fileMap.entrySet()) { - MultipartFile file = entry.getValue(); - if (!file.isEmpty()) { - formData.put(entry.getKey(), file); - } - } - } catch (Exception e) { - e.printStackTrace(); // Handle the exception according to your needs - } - return formData; - } - - @Operation( - summary = "Retrieving the Booking Details by BookingId REST API", - description = "REST API to get the Booking Details by Booking Id" - ) - //retrieving the Booking Details BY Booking ID - @GetMapping("/getBooking") - public ResponseEntity getBookingByID(@RequestParam int bookingId){ - return ResponseEntity.ok(bookingService.getBookingsById(bookingId)); - } - - @Operation( - summary = "User Booking Cancelling by BookingId REST API", - description = "REST API to Cancel the Booking by BookingId by User" - ) - //Booking Cancelling by BookingId + public Map splitFormData(MultipartHttpServletRequest multipartRequest) { + Map formData = new HashMap<>(); + + // Iterate through the request parameters + Enumeration parameterNames = multipartRequest.getParameterNames(); + while (parameterNames.hasMoreElements()) { + String paramName = parameterNames.nextElement(); + String paramValues = multipartRequest.getParameter(paramName); + formData.put(paramName, paramValues); + } + + // Iterate through the request parts (files) + try { + Map fileMap = multipartRequest.getFileMap(); + for (Map.Entry entry : fileMap.entrySet()) { + MultipartFile file = entry.getValue(); + if (!file.isEmpty()) { + formData.put(entry.getKey(), file); + } + } + } catch (Exception e) { + e.printStackTrace(); // Handle the exception according to your needs + } + return formData; + } + + @Operation( + summary = "Retrieving the Booking Details by BookingId REST API", + description = "REST API to get the Booking Details by Booking Id" + ) + //retrieving the Booking Details BY Booking ID + @GetMapping("/getBooking") + public ResponseEntity getBookingByID(@RequestParam int bookingId) { + return ResponseEntity.ok(bookingService.getBookingsById(bookingId)); + } + + @Operation( + summary = "User Booking Cancelling by BookingId REST API", + description = "REST API to Cancel the Booking by BookingId by User" + ) + //Booking Cancelling by BookingId //Booking Cancelling by BookingId -@GetMapping("/cancelBookingbyId") - public ResponseEntity cancelBooking(@RequestParam int bookingId, - @RequestParam BookingDetails.BookingStatus status, - @RequestParam String comments) { - log.info("Received request to cancel booking with ID: {}"); - log.info("Status: {}, Comments: {}"); - Optional bookings=bookingDetailsRepository.findById(bookingId); - BookingDetails bookingDetails=bookings.get(); - try { - BookingDetails cancelledBooking = bookingService.updateCancelledBookingStatus(bookingId, status, comments); - - String cancelledbookingsms="Your booking ID "+bookingId+" on "+bookingDetails.getStartDate()+" has been cancelled successfully. The deposit amount will be refunded to your account within 3 to 15 days. Thanks for using the GCC Community Hall Booking System."; - String cancelledurlString ="https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to="+bookingDetails.getUsers().getMobileNo()+"&from=GCCCRP&body="+cancelledbookingsms+"&entityid=1401572690000011081&templateid=1407172346829376988"; - String cancelledwhatsupmsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to="+bookingDetails.getUsers().getMobileNo()+"&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+booking+with+ID+"+bookingId+"+on+"+bookingDetails.getStartDate()+"+has+been+cancelled+successfully.+%0AThe+deposit+amount+will+be+refunded+to+your+account+within+3+to+15+days."; - whatsappMsgServiceImpl.sendMsg(cancelledwhatsupmsg); - whatsappMsgServiceImpl.sendSMS(cancelledurlString); - Optional book=bookingDetailsRepository.findById(bookingDetails.getBookingId()); - BookingDetails booking=book.get(); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); - String formattedDate = LocalDateTime.now().format(formatter); - booking.setUpdatedDate(formattedDate); - bookingDetailsRepository.save(booking); - log.info("Booking cancelled successfully"); - return ResponseEntity.ok(cancelledBooking); - } catch (Exception e) { - log.error("Error cancelling booking", e); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body("Error cancelling booking: " + e.getMessage()); - } -} - - @Operation( - summary = "Family Pensioner Details from ERP REST API", - description = "REST API to check the Family Pensioner Details From ERP" - ) - //checking Family pensioner Details - @GetMapping("/FamilyPensionerDetails") - @ResponseBody // Ensure Spring treats the returned object as the response body - public Map getFamilyPensionerDetails(HttpServletRequest request, @RequestParam("id") Long id) { - String purpose = "Checking Pensioner"; - RestTemplate restTemplate = new RestTemplate(); - String url = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?serviceId=getFamPensionerDetailsList&familPensionId=" - + id; - - ResponseEntity responseEntity = restTemplate.getForEntity(url, String.class); - - // Extract the JSON string from the response body - String jsonString = responseEntity.getBody(); - - // Extract the Java object from the response body - ObjectMapper objectMapper = new ObjectMapper(); - Map responseMap = new HashMap<>(); - - try { - FamilyPensionerDetailsResponse familyPensionerDetailsResponse = objectMapper.readValue(jsonString, - FamilyPensionerDetailsResponse.class); - - if (familyPensionerDetailsResponse != null) { - List familyPensionerDetails = familyPensionerDetailsResponse - .getFamilyPensionerDetails(); - - if (familyPensionerDetails != null && !familyPensionerDetails.isEmpty()) { - //Long mobileNo = Long.parseLong(familyPensionerDetailsResponse.getFamilyPensionerDetails().get(0).getMobile_no()); - - Long mobileNo = 8220798937l; - //System.out.println("step 1"); - responseMap.put("mobileNo", mobileNo); - } - } - } catch (IOException e) { - e.printStackTrace(); - } + @GetMapping("/cancelBookingbyId") + public ResponseEntity cancelBooking(@RequestParam int bookingId, + @RequestParam BookingDetails.BookingStatus status, + @RequestParam String comments) { + log.info("Received request to cancel booking with ID: {}"); + log.info("Status: {}, Comments: {}"); + Optional bookings = bookingDetailsRepository.findById(bookingId); + BookingDetails bookingDetails = bookings.get(); + try { + BookingDetails cancelledBooking = bookingService.updateCancelledBookingStatus(bookingId, status, comments); + + String cancelledbookingsms = "Your booking ID " + bookingId + " on " + bookingDetails.getStartDate() + " has been cancelled successfully. The deposit amount will be refunded to your account within 3 to 15 days. Thanks for using the GCC Community Hall Booking System."; + String cancelledurlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + bookingDetails.getUsers().getMobileNo() + "&from=GCCCRP&body=" + cancelledbookingsms + "&entityid=1401572690000011081&templateid=1407172346829376988"; + String cancelledwhatsupmsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + bookingDetails.getUsers().getMobileNo() + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+booking+with+ID+" + bookingId + "+on+" + bookingDetails.getStartDate() + "+has+been+cancelled+successfully.+%0AThe+deposit+amount+will+be+refunded+to+your+account+within+3+to+15+days."; + whatsappMsgServiceImpl.sendMsg(cancelledwhatsupmsg); + whatsappMsgServiceImpl.sendSMS(cancelledurlString); + Optional book = bookingDetailsRepository.findById(bookingDetails.getBookingId()); + BookingDetails booking = book.get(); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + String formattedDate = LocalDateTime.now().format(formatter); + booking.setUpdatedDate(formattedDate); + bookingDetailsRepository.save(booking); + log.info("Booking cancelled successfully"); + return ResponseEntity.ok(cancelledBooking); + } catch (Exception e) { + log.error("Error cancelling booking", e); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body("Error cancelling booking: " + e.getMessage()); + } + } - return responseMap; - } - - @Operation( - summary = "GCC Employee Details ERP REST API", - description = "REST API to retrieving the GCC Employee Details From ERP" - ) - @GetMapping("/gccemployee") - @ResponseBody // Ensure Spring treats the returned object as the response body - public Map getGccEmployee(HttpServletRequest request, @RequestParam("id") Long id) { - String purpose = "Checking GccEmployee"; - RestTemplate restTemplate = new RestTemplate(); - String url = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?serviceId=getEmployeeDetail&EmployeeID=" - + id; - - ResponseEntity responseEntity = restTemplate.getForEntity(url, String.class); - - // Extract the JSON string from the response body - String jsonString = responseEntity.getBody(); - - // Extract the Java object from the response body - ObjectMapper objectMapper = new ObjectMapper(); - Map responseMap = new HashMap<>(); - - try { - EmployeeDetailsResponse employeeDetailsResponse = objectMapper.readValue(jsonString, - EmployeeDetailsResponse.class); - - if (employeeDetailsResponse != null) { - List employeeDetails = employeeDetailsResponse - .getEmployeeDetailsResult(); - - if (employeeDetails != null && !employeeDetails.isEmpty()) { - //Long mobileNo = Long.parseLong(familyPensionerDetailsResponse.getFamilyPensionerDetails().get(0).getMobile_no()); - - //Long mobileNo = 8220798933l; - //System.out.println("step 1"); - responseMap.put("EmployeeDetailsResult", employeeDetails ); - }else { - responseMap.put("EmployeeDetailsResult", null ); - } - } - } catch (IOException e) { - e.printStackTrace(); - } + @Operation( + summary = "Family Pensioner Details from ERP REST API", + description = "REST API to check the Family Pensioner Details From ERP" + ) + //checking Family pensioner Details + @GetMapping("/FamilyPensionerDetails") + @ResponseBody // Ensure Spring treats the returned object as the response body + public Map getFamilyPensionerDetails(HttpServletRequest request, @RequestParam("id") Long id) { + String purpose = "Checking Pensioner"; + RestTemplate restTemplate = new RestTemplate(); + String url = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?serviceId=getFamPensionerDetailsList&familPensionId=" + + id; - return responseMap; - } - - @Operation( - summary = "Pensioner Details ERP REST API", - description = "REST API to retrieving the Pensioner Details From ERP" - ) - //checking pensioner Details - @GetMapping("/PensionerDetails") - @ResponseBody - public Map getPensionerDetails(HttpServletRequest request, @RequestParam("id") Long id) { - String purpose = "Checking Employee"; - RestTemplate restTemplate = new RestTemplate(); - String url = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?serviceId=getPensionerDetailsList&pensionerId=" + id; - - ResponseEntity responseEntity = restTemplate.getForEntity(url, String.class); - - // Extract the JSON string from the response body - String jsonString = responseEntity.getBody(); - - // Extract the Java object from the response body - ObjectMapper objectMapper = new ObjectMapper(); - Map responseMap = new HashMap<>(); - - try { - PensionerDetailsResponse pensionerDetailsResponse = objectMapper.readValue(jsonString, PensionerDetailsResponse.class); - - if (pensionerDetailsResponse != null) { - List pensionerDetails = pensionerDetailsResponse.getEmployees(); - - if (pensionerDetails != null && !pensionerDetails.isEmpty()) { - Long mobileNo = Long.parseLong(pensionerDetailsResponse.getEmployees().get(0).getMobile_no()); + ResponseEntity responseEntity = restTemplate.getForEntity(url, String.class); + + // Extract the JSON string from the response body + String jsonString = responseEntity.getBody(); + + // Extract the Java object from the response body + ObjectMapper objectMapper = new ObjectMapper(); + Map responseMap = new HashMap<>(); + + try { + FamilyPensionerDetailsResponse familyPensionerDetailsResponse = objectMapper.readValue(jsonString, + FamilyPensionerDetailsResponse.class); + + if (familyPensionerDetailsResponse != null) { + List familyPensionerDetails = familyPensionerDetailsResponse + .getFamilyPensionerDetails(); + + if (familyPensionerDetails != null && !familyPensionerDetails.isEmpty()) { + //Long mobileNo = Long.parseLong(familyPensionerDetailsResponse.getFamilyPensionerDetails().get(0).getMobile_no()); + + Long mobileNo = 8220798937l; + //System.out.println("step 1"); + responseMap.put("mobileNo", mobileNo); + } + } + } catch (IOException e) { + e.printStackTrace(); + } + + return responseMap; + } + + @Operation( + summary = "GCC Employee Details ERP REST API", + description = "REST API to retrieving the GCC Employee Details From ERP" + ) + @GetMapping("/gccemployee") + @ResponseBody // Ensure Spring treats the returned object as the response body + public Map getGccEmployee(HttpServletRequest request, @RequestParam("id") Long id) { + String purpose = "Checking GccEmployee"; + RestTemplate restTemplate = new RestTemplate(); + String url = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?serviceId=getEmployeeDetail&EmployeeID=" + + id; + + ResponseEntity responseEntity = restTemplate.getForEntity(url, String.class); + + // Extract the JSON string from the response body + String jsonString = responseEntity.getBody(); + + // Extract the Java object from the response body + ObjectMapper objectMapper = new ObjectMapper(); + Map responseMap = new HashMap<>(); + + try { + EmployeeDetailsResponse employeeDetailsResponse = objectMapper.readValue(jsonString, + EmployeeDetailsResponse.class); + + if (employeeDetailsResponse != null) { + List employeeDetails = employeeDetailsResponse + .getEmployeeDetailsResult(); + + if (employeeDetails != null && !employeeDetails.isEmpty()) { + //Long mobileNo = Long.parseLong(familyPensionerDetailsResponse.getFamilyPensionerDetails().get(0).getMobile_no()); + + //Long mobileNo = 8220798933l; + //System.out.println("step 1"); + responseMap.put("EmployeeDetailsResult", employeeDetails); + } else { + responseMap.put("EmployeeDetailsResult", null); + } + } + } catch (IOException e) { + e.printStackTrace(); + } + + return responseMap; + } + + @Operation( + summary = "Pensioner Details ERP REST API", + description = "REST API to retrieving the Pensioner Details From ERP" + ) + //checking pensioner Details + @GetMapping("/PensionerDetails") + @ResponseBody + public Map getPensionerDetails(HttpServletRequest request, @RequestParam("id") Long id) { + String purpose = "Checking Employee"; + RestTemplate restTemplate = new RestTemplate(); + String url = "https://erp.chennaicorporation.gov.in/pgr/external/mobileservice?serviceId=getPensionerDetailsList&pensionerId=" + id; + + ResponseEntity responseEntity = restTemplate.getForEntity(url, String.class); + + // Extract the JSON string from the response body + String jsonString = responseEntity.getBody(); + + // Extract the Java object from the response body + ObjectMapper objectMapper = new ObjectMapper(); + Map responseMap = new HashMap<>(); + + try { + PensionerDetailsResponse pensionerDetailsResponse = objectMapper.readValue(jsonString, PensionerDetailsResponse.class); + + if (pensionerDetailsResponse != null) { + List pensionerDetails = pensionerDetailsResponse.getEmployees(); + + if (pensionerDetails != null && !pensionerDetails.isEmpty()) { + Long mobileNo = Long.parseLong(pensionerDetailsResponse.getEmployees().get(0).getMobile_no()); // Long mobileNo = 9874561230l; - // System.out.println("step 2"); - responseMap.put("mobileNo", mobileNo); - return responseMap; - } else { - responseMap.put("error", "No pensioner details found for the given ID"); - return responseMap; - } - } + // System.out.println("step 2"); + responseMap.put("mobileNo", mobileNo); + return responseMap; + } else { + responseMap.put("error", "No pensioner details found for the given ID"); + return responseMap; + } + } - } catch (Exception e) { - e.printStackTrace(); - responseMap.put("error", "An error occurred while processing the request"); - } + } catch (Exception e) { + e.printStackTrace(); + responseMap.put("error", "An error occurred while processing the request"); + } - return responseMap; - } - - @Operation( - summary = "Saving Counter Details ERP REST API", - description = "REST API to save the Counter Details" - ) - //Saving the Counter Details - @PostMapping(path = "/counter-booking", consumes = { "multipart/form-data" }) - public ResponseEntity saveCounterBookingDetails(HttpServletRequest request) { - MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; - Map bookingDetails = splitFormData(multipartRequest); - Map saveCounterBooking = counterService.saveCounterBooking(bookingDetails); - return ResponseEntity.ok(saveCounterBooking); - } - @GetMapping("/checkAvail") - public List checkAvail(@RequestParam("fromDate") String fromDate, - @RequestParam("toDate") String toDate, - @RequestParam("starting") String starting, - @RequestParam("ending") String ending, - @RequestParam(name = "hallId",required = false) String hallId){ - List data = new ArrayList<>(); - HashSet removeHallId = new HashSet(); - int hallIdd=0; - if(hallId != null && !hallId.equals("")){ - hallIdd = Integer.parseInt(hallId); - } - if(!fromDate.equals(toDate) && (starting.equals(ending) || starting.equals("evening") && ending.equals("morning"))){ - Map mp =incrementAndDecrementAndDaysCount(fromDate,toDate); - long noOfDays= Long.parseLong(mp.get("NoOfDays").toString()); - if(noOfDays>2){ - data = calendarService.getCalendarByDateAndHallIdAndSlot(mp.get("fromDate"),mp.get("toDate"),starting,ending,hallIdd); - for(int i=0;i removeHallByid = new ArrayList<>(); - if(hallIdd!=0){ - if(hallIdd!=data.get(0).getHallId()){ - HallDetails hallDetails = hallDetailService.getHallById(hallIdd); - removeHallByid.add(hallDetails); - } + @Operation( + summary = "Saving Counter Details ERP REST API", + description = "REST API to save the Counter Details" + ) + //Saving the Counter Details + @PostMapping(path = "/counter-booking", consumes = {"multipart/form-data"}) + public ResponseEntity saveCounterBookingDetails(HttpServletRequest request) { + MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; + Map bookingDetails = splitFormData(multipartRequest); + Map saveCounterBooking = counterService.saveCounterBooking(bookingDetails); + return ResponseEntity.ok(saveCounterBooking); + } - }else { - removeHallByid = hallDetailService.removeHallById(removeHallId); - } - return removeHallByid; - } - - Map incrementAndDecrementAndDaysCount(String fromdate, String todate){ - Map mp = new HashMap<>(); - LocalDate increasement = LocalDate.parse(fromdate); - LocalDate decrement = LocalDate.parse(todate); + @GetMapping("/checkAvail") + public List checkAvail(@RequestParam("fromDate") String fromDate, + @RequestParam("toDate") String toDate, + @RequestParam("starting") String starting, + @RequestParam("ending") String ending, + @RequestParam(name = "hallId", required = false) String hallId) { + List data = new ArrayList<>(); + HashSet removeHallId = new HashSet(); + int hallIdd = 0; + if (hallId != null && !hallId.equals("")) { + hallIdd = Integer.parseInt(hallId); + } + if (!fromDate.equals(toDate) && (starting.equals(ending) || starting.equals("evening") && ending.equals("morning"))) { + Map mp = incrementAndDecrementAndDaysCount(fromDate, toDate); + long noOfDays = Long.parseLong(mp.get("NoOfDays").toString()); + if (noOfDays > 2) { + data = calendarService.getCalendarByDateAndHallIdAndSlot(mp.get("fromDate"), mp.get("toDate"), starting, ending, hallIdd); + for (int i = 0; i < data.size(); i++) { + removeHallId.add(data.get(i).getHallId()); + } + } + } - LocalDate outputDateFrom =increasement; - LocalDate outputDateToday = decrement; + data = calendarService.getCalendarByDateAndHallIdAndSlot(fromDate, toDate, starting, ending, hallIdd); + //System.out.println("data size :-"+data.size()); + + if (starting != null && ending != null) { + boolean checkAvail = false; + int checkHallId = 0; + for (int i = 0; i < data.size(); i++) { + + if ((starting.equals("evening") || ending.equals("morning")) && fromDate.equals(data.get(i).getBdate().toString()) && toDate.equals(fromDate)) { + if (data.get(i).isEveningSlot() == false) { + continue; + } else if (data.get(i).isMorningSlot() == false) { + continue; + } + } else if ((starting.equals(ending) || starting.equals("evening") && ending.equals("morning")) && !toDate.equals(fromDate)) { + if (checkHallId == 0 || checkHallId != data.get(i).getHallId()) { + checkHallId = data.get(i).getHallId(); + checkAvail = false; + } + + if (starting.equals("morning") && ending.equals("morning")) { + if (fromDate.equals(data.get(i).getBdate().toString()) && data.get(i).isMorningSlot() == false) { + if (checkHallId == data.get(i).getHallId()) { + + continue; + } + } else if (toDate.equals(data.get(i).getBdate().toString()) && data.get(i).isMorningSlot() == false) { + if (checkHallId == data.get(i).getHallId() && checkAvail == false) { + checkHallId = data.get(i).getHallId(); + continue; + } + } + } else if (starting.equals("evening") && ending.equals("morning")) { + + if (fromDate.equals(data.get(i).getBdate().toString()) && data.get(i).isEveningSlot() == false) { + if (checkHallId == data.get(i).getHallId()) { + continue; + } + } else if (toDate.equals(data.get(i).getBdate().toString()) && data.get(i).isMorningSlot() == false) { + if (checkHallId == data.get(i).getHallId() && checkAvail == false) { + checkHallId = data.get(i).getHallId(); + continue; + } + } + } else if (starting.equals("evening") && ending.equals("evening")) { + if (fromDate.equals(data.get(i).getBdate().toString()) && data.get(i).isEveningSlot() == false) { + if (checkHallId == data.get(i).getHallId()) { + continue; + } + } else if (toDate.equals(data.get(i).getBdate().toString()) && data.get(i).isEveningSlot() == false) { + if (checkHallId == data.get(i).getHallId() && checkAvail == false) { + checkHallId = data.get(i).getHallId(); + continue; + } + } + } else { + if (checkHallId == data.get(i).getHallId()) { + checkAvail = true; + } + } + } + //System.out.println(data.get(i).getHallId()); + removeHallId.add(data.get(i).getHallId()); + } + } + List removeHallByid = new ArrayList<>(); + if (hallIdd != 0) { + if (hallIdd != data.get(0).getHallId()) { + HallDetails hallDetails = hallDetailService.getHallById(hallIdd); + removeHallByid.add(hallDetails); + } - long daysDifference = increasement.until(decrement).getDays(); - daysDifference = Math.abs(daysDifference); + } else { + removeHallByid = hallDetailService.removeHallById(removeHallId); + } + return removeHallByid; + } - if(fromdate!=todate) { - outputDateFrom = increasement.plusDays(1); - outputDateToday = decrement.minusDays(1); - } + Map incrementAndDecrementAndDaysCount(String fromdate, String todate) { + Map mp = new HashMap<>(); + LocalDate increasement = LocalDate.parse(fromdate); + LocalDate decrement = LocalDate.parse(todate); - mp.put("fromDate", outputDateFrom.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))); - mp.put("toDate",outputDateToday.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))); - mp.put("NoOfDays",daysDifference+""); - return mp; - } - - @GetMapping("/getuserDetailsbymobileno") - public Users getuserDetailsbymobileno(@RequestParam long mobileNo) { - return userservice.getUserDetailsByMobileNo(mobileNo); + LocalDate outputDateFrom = increasement; + LocalDate outputDateToday = decrement; - } - - //Reschedule - @PostMapping("/reschedule-dates") - public ResponseEntity updateBookingDates( - @RequestParam int bookingId, - @RequestParam String startDate, - @RequestParam String endDate) { - try { - Optional updateResult = bookingService.updateBookingDatesAndCalendar(bookingId, startDate, endDate); - if (updateResult.isPresent()) { - if (updateResult.get().equals("Booking dates updated successfully.")) { - return new ResponseEntity<>(updateResult.get(), HttpStatus.OK); - } else { - // Any other message is treated as an error - return new ResponseEntity<>(updateResult.get(), HttpStatus.BAD_REQUEST); - } - } else { - return new ResponseEntity<>("Booking not found", HttpStatus.NOT_FOUND); - } - } catch (SlotOccupiedException e) { - // Return a bad request status with the exception message - return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST); - } - } - - @GetMapping("/trackBooking") - public List> getTrackingDetails(@RequestParam int bookingId) { - Optional booking = bookingDetailsRepository.findById(bookingId); - List> trackingDetails = new ArrayList<>(); - DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); - DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"); - - if (booking.isPresent()) { - BookingDetails bookingDetails = booking.get(); - - // Payment Success - if (bookingDetails.getPayments() != null) { - Map paymentDetail = new HashMap<>(); - paymentDetail.put("status", "PAYMENT_SUCCESS"); - paymentDetail.put("description", "Payment Success"); - paymentDetail.put("dateTime", bookingDetails.getPayments().getCdate()); // Assuming Cdate is the created date - trackingDetails.add(paymentDetail); - } + long daysDifference = increasement.until(decrement).getDays(); + daysDifference = Math.abs(daysDifference); - // Booking Approved - if (bookingDetails.getBookingStatus() == BookingStatus.APPROVED) { - Map bookingApprovedDetail = new HashMap<>(); - bookingApprovedDetail.put("status", "APPROVED"); - bookingApprovedDetail.put("description", "Booking Approved"); - bookingApprovedDetail.put("dateTime", bookingDetails.getBookingDate()); // Assuming BookingDate is correct - trackingDetails.add(bookingApprovedDetail); - } + if (fromdate != todate) { + outputDateFrom = increasement.plusDays(1); + outputDateToday = decrement.minusDays(1); + } - // Event Completed - LocalDateTime endDate = null; - try { - // Try parsing as LocalDateTime first - try { - endDate = LocalDateTime.parse(bookingDetails.getEndDate(), dateTimeFormatter); - } catch (Exception e) { - // If parsing fails, try parsing as LocalDate - LocalDate endDateOnly = LocalDate.parse(bookingDetails.getEndDate(), dateFormatter); - endDate = endDateOnly.atStartOfDay(); // Convert LocalDate to LocalDateTime at start of the day - } - } catch (Exception e) { - // Handle parsing exception - e.printStackTrace(); - } + mp.put("fromDate", outputDateFrom.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))); + mp.put("toDate", outputDateToday.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))); + mp.put("NoOfDays", daysDifference + ""); + return mp; + } - if (endDate != null && bookingDetails.getBookingStatus() == BookingStatus.APPROVED && - endDate.isBefore(LocalDateTime.now().plusDays(1))) { // Compare endDate with current date - Map eventCompletedDetail = new HashMap<>(); - eventCompletedDetail.put("status", "EVENT_COMPLETED"); - eventCompletedDetail.put("description", "Event Completed"); - eventCompletedDetail.put("dateTime", bookingDetails.getEndDate()); - trackingDetails.add(eventCompletedDetail); - } + @GetMapping("/getuserDetailsbymobileno") + public Users getuserDetailsbymobileno(@RequestParam long mobileNo) { + return userservice.getUserDetailsByMobileNo(mobileNo); - // Settlement Raising - if (bookingDetails.getSettlement() != null && bookingDetails.getRefundStatus() == RefundStatus.WAITING) { - Map settlementRaisingDetail = new HashMap<>(); - settlementRaisingDetail.put("status", "SETTLEMENT_RAISING"); - settlementRaisingDetail.put("description", "Settlement Raising"); - settlementRaisingDetail.put("dateTime", bookingDetails.getSettlement().getUpdatedDate() ); - trackingDetails.add(settlementRaisingDetail); - } + } - // Refund Completed - if (bookingDetails.getBookingStatus() == BookingStatus.COMPLETED - && bookingDetails.getRefundStatus() == BookingDetails.RefundStatus.COMPLETED) { - Map refundCompletedDetail = new HashMap<>(); - refundCompletedDetail.put("status", "COMPLETED"); - refundCompletedDetail.put("description", "Refund Completed"); - refundCompletedDetail.put("dateTime", bookingDetails.getUpdatedDate()); - trackingDetails.add(refundCompletedDetail); - } + //Reschedule + @PostMapping("/reschedule-dates") + public ResponseEntity updateBookingDates( + @RequestParam int bookingId, + @RequestParam String startDate, + @RequestParam String endDate) { + try { + Optional updateResult = bookingService.updateBookingDatesAndCalendar(bookingId, startDate, endDate); + if (updateResult.isPresent()) { + if (updateResult.get().equals("Booking dates updated successfully.")) { + return new ResponseEntity<>(updateResult.get(), HttpStatus.OK); + } else { + // Any other message is treated as an error + return new ResponseEntity<>(updateResult.get(), HttpStatus.BAD_REQUEST); + } + } else { + return new ResponseEntity<>("Booking not found", HttpStatus.NOT_FOUND); + } + } catch (SlotOccupiedException e) { + // Return a bad request status with the exception message + return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST); + } + } + @GetMapping("/trackBooking") + public List> getTrackingDetails(@RequestParam int bookingId) { + Optional booking = bookingDetailsRepository.findById(bookingId); + List> trackingDetails = new ArrayList<>(); + DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"); + + if (booking.isPresent()) { + BookingDetails bookingDetails = booking.get(); + + // Payment Success + if (bookingDetails.getPayments() != null) { + Map paymentDetail = new HashMap<>(); + paymentDetail.put("status", "PAYMENT_SUCCESS"); + paymentDetail.put("description", "Payment Success"); + paymentDetail.put("dateTime", bookingDetails.getPayments().getCdate()); // Assuming Cdate is the created date + trackingDetails.add(paymentDetail); + } - if (bookingDetails.getBookingStatus() == BookingStatus.CANCELED){ - Map bookingCanceledDetail = new HashMap<>(); - bookingCanceledDetail.put("status","CANCELED"); - bookingCanceledDetail.put("description", "Booking Cancelled"); - bookingCanceledDetail.put("dateTime", bookingDetails.getUpdatedDate()); // Assuming BookingDate is correct - trackingDetails.add(bookingCanceledDetail); - } + // Booking Approved + if (bookingDetails.getBookingStatus() == BookingStatus.APPROVED) { + Map bookingApprovedDetail = new HashMap<>(); + bookingApprovedDetail.put("status", "APPROVED"); + bookingApprovedDetail.put("description", "Booking Approved"); + bookingApprovedDetail.put("dateTime", bookingDetails.getBookingDate()); // Assuming BookingDate is correct + trackingDetails.add(bookingApprovedDetail); + } + // Event Completed + LocalDateTime endDate = null; + try { + // Try parsing as LocalDateTime first + try { + endDate = LocalDateTime.parse(bookingDetails.getEndDate(), dateTimeFormatter); + } catch (Exception e) { + // If parsing fails, try parsing as LocalDate + LocalDate endDateOnly = LocalDate.parse(bookingDetails.getEndDate(), dateFormatter); + endDate = endDateOnly.atStartOfDay(); // Convert LocalDate to LocalDateTime at start of the day + } + } catch (Exception e) { + // Handle parsing exception + e.printStackTrace(); + } - if (bookingDetails.getBookingStatus() == BookingStatus.CANCELED - && bookingDetails.getRefundStatus() == RefundStatus.WAITING){ - Map canceledRaisingDetail = new HashMap<>(); - canceledRaisingDetail.put("status","SETTLEMENT_RAISING"); - canceledRaisingDetail.put("description", "Settlement Raising"); - canceledRaisingDetail.put("dateTime", bookingDetails.getUpdatedDate()); // Assuming BookingDate is correct - trackingDetails.add(canceledRaisingDetail); - } + if (endDate != null && bookingDetails.getBookingStatus() == BookingStatus.APPROVED && + endDate.isBefore(LocalDateTime.now().plusDays(1))) { // Compare endDate with current date + Map eventCompletedDetail = new HashMap<>(); + eventCompletedDetail.put("status", "EVENT_COMPLETED"); + eventCompletedDetail.put("description", "Event Completed"); + eventCompletedDetail.put("dateTime", bookingDetails.getEndDate()); + trackingDetails.add(eventCompletedDetail); + } - if (bookingDetails.getBookingStatus() == BookingStatus.CANCELED - && bookingDetails.getRefundStatus() == BookingDetails.RefundStatus.COMPLETED){ - Map cancelRefundCompletedDetail = new HashMap<>(); - cancelRefundCompletedDetail.put("status", "COMPLETED"); - cancelRefundCompletedDetail.put("description", "Refund Completed"); - cancelRefundCompletedDetail.put("dateTime", bookingDetails.getUpdatedDate()); - trackingDetails.add(cancelRefundCompletedDetail); - } + // Settlement Raising + if (bookingDetails.getSettlement() != null && bookingDetails.getRefundStatus() == RefundStatus.WAITING) { + Map settlementRaisingDetail = new HashMap<>(); + settlementRaisingDetail.put("status", "SETTLEMENT_RAISING"); + settlementRaisingDetail.put("description", "Settlement Raising"); + settlementRaisingDetail.put("dateTime", bookingDetails.getSettlement().getUpdatedDate()); + trackingDetails.add(settlementRaisingDetail); + } - if (bookingDetails.getBookingStatus() == BookingStatus.REJECTED){ - Map bookingRejectedDetail = new HashMap<>(); - bookingRejectedDetail.put("status","REJECTED"); - bookingRejectedDetail.put("description", "Booking Rejected"); - bookingRejectedDetail.put("dateTime", bookingDetails.getUpdatedDate()); // Assuming BookingDate is correct - trackingDetails.add(bookingRejectedDetail); - } + // Refund Completed + if (bookingDetails.getBookingStatus() == BookingStatus.COMPLETED + && bookingDetails.getRefundStatus() == BookingDetails.RefundStatus.COMPLETED) { + Map refundCompletedDetail = new HashMap<>(); + refundCompletedDetail.put("status", "COMPLETED"); + refundCompletedDetail.put("description", "Refund Completed"); + refundCompletedDetail.put("dateTime", bookingDetails.getUpdatedDate()); + trackingDetails.add(refundCompletedDetail); + } - if (bookingDetails.getBookingStatus() == BookingStatus.REJECTED - && bookingDetails.getRefundStatus() == RefundStatus.WAITING){ - Map rejectedRaisingDetail = new HashMap<>(); - rejectedRaisingDetail.put("status","SETTLEMENT_RAISING"); - rejectedRaisingDetail.put("description", "Settlement Raising"); - rejectedRaisingDetail.put("dateTime", bookingDetails.getUpdatedDate()); // Assuming BookingDate is correct - trackingDetails.add(rejectedRaisingDetail); - } + if (bookingDetails.getBookingStatus() == BookingStatus.CANCELED) { + Map bookingCanceledDetail = new HashMap<>(); + bookingCanceledDetail.put("status", "CANCELED"); + bookingCanceledDetail.put("description", "Booking Cancelled"); + bookingCanceledDetail.put("dateTime", bookingDetails.getUpdatedDate()); // Assuming BookingDate is correct + trackingDetails.add(bookingCanceledDetail); + } - if (bookingDetails.getBookingStatus() == BookingStatus.REJECTED - && bookingDetails.getRefundStatus() == BookingDetails.RefundStatus.COMPLETED){ - Map rejectedRefundCompletedDetail = new HashMap<>(); - rejectedRefundCompletedDetail.put("status", "COMPLETED"); - rejectedRefundCompletedDetail.put("description", "Refund Completed"); - rejectedRefundCompletedDetail.put("dateTime", bookingDetails.getUpdatedDate()); - trackingDetails.add(rejectedRefundCompletedDetail); - } + if (bookingDetails.getBookingStatus() == BookingStatus.CANCELED + && bookingDetails.getRefundStatus() == RefundStatus.WAITING) { + Map canceledRaisingDetail = new HashMap<>(); + canceledRaisingDetail.put("status", "SETTLEMENT_RAISING"); + canceledRaisingDetail.put("description", "Settlement Raising"); + canceledRaisingDetail.put("dateTime", bookingDetails.getUpdatedDate()); // Assuming BookingDate is correct + trackingDetails.add(canceledRaisingDetail); + } + if (bookingDetails.getBookingStatus() == BookingStatus.CANCELED + && bookingDetails.getRefundStatus() == BookingDetails.RefundStatus.COMPLETED) { + Map cancelRefundCompletedDetail = new HashMap<>(); + cancelRefundCompletedDetail.put("status", "COMPLETED"); + cancelRefundCompletedDetail.put("description", "Refund Completed"); + cancelRefundCompletedDetail.put("dateTime", bookingDetails.getUpdatedDate()); + trackingDetails.add(cancelRefundCompletedDetail); + } - if (bookingDetails.getBookingStatus() == BookingStatus.GCC_BLOCKED){ - Map gccBlockedDetail = new HashMap<>(); - gccBlockedDetail.put("status","GCC_BLOCKED"); - gccBlockedDetail.put("description", "GCC Blocked"); - gccBlockedDetail.put("dateTime", bookingDetails.getUpdatedDate()); - trackingDetails.add(gccBlockedDetail); - } - } - return trackingDetails; - } + if (bookingDetails.getBookingStatus() == BookingStatus.REJECTED) { + Map bookingRejectedDetail = new HashMap<>(); + bookingRejectedDetail.put("status", "REJECTED"); + bookingRejectedDetail.put("description", "Booking Rejected"); + bookingRejectedDetail.put("dateTime", bookingDetails.getUpdatedDate()); // Assuming BookingDate is correct + trackingDetails.add(bookingRejectedDetail); + } - @GetMapping("/confirmstatebooking") - public String Confirmstatebookig(@RequestParam int bookingId ) { - String response=bookingService.confirmStateBooking(bookingId); - return response; - } - - @PostMapping("/uploaddocs") - public ResponseEntity uploadDocs(@RequestParam("nocFile") MultipartFile file, - @RequestParam("bookingssId") int bookingId) { - try { - bookingService.uploadNOCFile(file, bookingId); - return ResponseEntity.ok("File uploaded and saved successfully"); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("File upload failed: " + e.getMessage()); - } - } + if (bookingDetails.getBookingStatus() == BookingStatus.REJECTED + && bookingDetails.getRefundStatus() == RefundStatus.WAITING) { + Map rejectedRaisingDetail = new HashMap<>(); + rejectedRaisingDetail.put("status", "SETTLEMENT_RAISING"); + rejectedRaisingDetail.put("description", "Settlement Raising"); + rejectedRaisingDetail.put("dateTime", bookingDetails.getUpdatedDate()); // Assuming BookingDate is correct + trackingDetails.add(rejectedRaisingDetail); + } + + if (bookingDetails.getBookingStatus() == BookingStatus.REJECTED + && bookingDetails.getRefundStatus() == BookingDetails.RefundStatus.COMPLETED) { + Map rejectedRefundCompletedDetail = new HashMap<>(); + rejectedRefundCompletedDetail.put("status", "COMPLETED"); + rejectedRefundCompletedDetail.put("description", "Refund Completed"); + rejectedRefundCompletedDetail.put("dateTime", bookingDetails.getUpdatedDate()); + trackingDetails.add(rejectedRefundCompletedDetail); + } + + + if (bookingDetails.getBookingStatus() == BookingStatus.GCC_BLOCKED) { + Map gccBlockedDetail = new HashMap<>(); + gccBlockedDetail.put("status", "GCC_BLOCKED"); + gccBlockedDetail.put("description", "GCC Blocked"); + gccBlockedDetail.put("dateTime", bookingDetails.getUpdatedDate()); + trackingDetails.add(gccBlockedDetail); + } + } + return trackingDetails; + } + + + @GetMapping("/confirmstatebooking") + public String Confirmstatebookig(@RequestParam int bookingId) { + String response = bookingService.confirmStateBooking(bookingId); + return response; + } + + @PostMapping("/uploaddocs") + public ResponseEntity uploadDocs(@RequestParam("nocFile") MultipartFile file, + @RequestParam("bookingssId") int bookingId) { + try { + bookingService.uploadNOCFile(file, bookingId); + return ResponseEntity.ok("File uploaded and saved successfully"); + } catch (Exception e) { + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("File upload failed: " + e.getMessage()); + } + } /*@GetMapping("/calculatehallamount") public ResponseEntity> getHallDetailsConcession( @RequestParam int numDays, @@ -1734,22 +1745,22 @@ public class UserAPIController { response.put("amount", amount); response.put("totalAmount", totalAmount); response.put("depositAmount", totalDepositAmount); - double gstValue =gstRate * amount / 100.0; + double gstValue = gstRate * amount / 100.0; response.put("gst", gstValue); response.put("discountAmount", amount); } else { if ("SGE".equals(reasonforBooking)) { double cleaningCharges = hallDetails.getHallDetailsConcession().get(0).getFullDayCleaningcharges(); - double pasystem=hallDetails.getHallDetailsConcession().get(0).getFulldayPAsystem(); - double ebCharges=hallDetails.getHallDetailsConcession().get(0).getFulldayEBcharges(); + double pasystem = hallDetails.getHallDetailsConcession().get(0).getFulldayPAsystem(); + double ebCharges = hallDetails.getHallDetailsConcession().get(0).getFulldayEBcharges(); double halfcleaningCharges = hallDetails.getHallDetailsConcession().get(0).getHalfDayCleaningcharges(); - double halfpasystem=hallDetails.getHallDetailsConcession().get(0).getHalfdayPAsystem(); - double halfebCharges=hallDetails.getHallDetailsConcession().get(0).getHalfdayEBcharges(); - double fulladditionalCharges = cleaningCharges+pasystem+ebCharges; - double halfadditionalCharges = halfcleaningCharges+halfpasystem+halfebCharges; - double fulldayhallAmount=hallDetails.getHallDetailsConcession().get(0).getFulldayhallamount(); - double halfdayhallAmount=hallDetails.getHallDetailsConcession().get(0).getHalfdayhallamount(); - double additionalCharges=calculateAmount(numDays, startPeriod, endPeriod, fulladditionalCharges, halfadditionalCharges); + double halfpasystem = hallDetails.getHallDetailsConcession().get(0).getHalfdayPAsystem(); + double halfebCharges = hallDetails.getHallDetailsConcession().get(0).getHalfdayEBcharges(); + double fulladditionalCharges = cleaningCharges + pasystem + ebCharges; + double halfadditionalCharges = halfcleaningCharges + halfpasystem + halfebCharges; + double fulldayhallAmount = hallDetails.getHallDetailsConcession().get(0).getFulldayhallamount(); + double halfdayhallAmount = hallDetails.getHallDetailsConcession().get(0).getHalfdayhallamount(); + double additionalCharges = calculateAmount(numDays, startPeriod, endPeriod, fulladditionalCharges, halfadditionalCharges); totalAmount = additionalCharges + totalDepositAmount + (additionalCharges * gstRate / 100.0); discountAmount = (fulldayhallAmount * hallDetails.getSGEdiscount()) / 100.0; response.put("startperiod", startPeriod); @@ -1766,18 +1777,18 @@ public class UserAPIController { 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(); + double pasystem = hallDetails.getHallDetailsConcession().get(0).getFulldayPAsystem(); + double ebCharges = hallDetails.getHallDetailsConcession().get(0).getFulldayEBcharges(); double halfcleaningCharges = hallDetails.getHallDetailsConcession().get(0).getHalfDayCleaningcharges(); - double halfpasystem=hallDetails.getHallDetailsConcession().get(0).getHalfdayPAsystem(); - double halfebCharges=hallDetails.getHallDetailsConcession().get(0).getHalfdayEBcharges(); - double fulladditionalCharges = cleaningCharges+pasystem+ebCharges; - double halfadditionalCharges = halfcleaningCharges+halfpasystem+halfebCharges; - double additionalCharges=calculateAmount(numDays, startPeriod, endPeriod, fulladditionalCharges, halfadditionalCharges); + double halfpasystem = hallDetails.getHallDetailsConcession().get(0).getHalfdayPAsystem(); + double halfebCharges = hallDetails.getHallDetailsConcession().get(0).getHalfdayEBcharges(); + double fulladditionalCharges = cleaningCharges + pasystem + ebCharges; + double halfadditionalCharges = halfcleaningCharges + halfpasystem + halfebCharges; + double additionalCharges = calculateAmount(numDays, startPeriod, endPeriod, fulladditionalCharges, halfadditionalCharges); double rentAmount = (amount * hallDetails.getCGEdiscount()) / 100.0; double netAmount = rentAmount + additionalCharges; - double gst = ((additionalCharges+rentAmount) * gstRate / 100.0); - totalAmount = Math.floor((netAmount + gst + totalDepositAmount) * 100) / 100.0 ; + double gst = ((additionalCharges + rentAmount) * gstRate / 100.0); + totalAmount = Math.floor((netAmount + gst + totalDepositAmount) * 100) / 100.0; response.put("startperiod", startPeriod); response.put("endPeriod", endPeriod); response.put("fulldayhallAmount", fullDayAmount); @@ -1791,7 +1802,7 @@ public class UserAPIController { response.put("totalAmount", totalAmount); response.put("discountAmount", discountAmount); } else { - double gstValue =(gstRate * amount) / 100.0; + double gstValue = (gstRate * amount) / 100.0; totalAmount = Math.ceil((amount + gstValue + totalDepositAmount) * 100) / 100; response.put("discount", 0); response.put("amount", amount); @@ -1804,6 +1815,7 @@ public class UserAPIController { return ResponseEntity.ok(response); } + public double calculateAmount(double numDays, String startPeriod, String endPeriod, double fullDayAmount, double halfDayAmount) { double amount = 0; @@ -1815,8 +1827,8 @@ public class UserAPIController { amount = halfDayAmount; } else if ("2".equals(startPeriod) && "2".equals(endPeriod)) { amount = halfDayAmount; - }else { - amount=numDays; + } else { + amount = numDays; } } else { // For multiple days @@ -1828,40 +1840,40 @@ public class UserAPIController { amount = fullDayAmount * (numDays - 1) + halfDayAmount; } else if ("2".equals(startPeriod) && "1".equals(endPeriod)) { amount = fullDayAmount * (numDays - 2) + halfDayAmount * 2; - }else { - amount=numDays; + } else { + amount = numDays; } } return amount; } - @GetMapping("/getTransactionDetails") - public Map getTransactionDetails(@RequestParam String userId) { - // Fetch all transaction details for the user - List transactions = PaymentGatewayServiceImpl.getTransactionResponseByuserId(userId); - - Map response = new HashMap<>(); - response.put("transactions", transactions); + @GetMapping("/getTransactionDetails") + public Map getTransactionDetails(@RequestParam String userId) { + // Fetch all transaction details for the user + List transactions = PaymentGatewayServiceImpl.getTransactionResponseByuserId(userId); + + Map response = new HashMap<>(); + response.put("transactions", transactions); - // Fetch all refund details for the user in a single query - List refundDetails = transRefundResRepository.getRefundResponseByuserId(userId); + // Fetch all refund details for the user in a single query + List refundDetails = transRefundResRepository.getRefundResponseByuserId(userId); - response.put("refundDetails", refundDetails); + response.put("refundDetails", refundDetails); - System.out.println("Response: " + response); + System.out.println("Response: " + response); - return response; - } + return response; + } - @GetMapping("/collectionpendingacknowledgementsss") - public BookingDetails viewCollectionpendingAck(Model model,int bookingId){ - BookingDetails bookingsDetails = bookingService.getBookingsById(bookingId); - model.addAttribute("bookingsDetails",bookingsDetails); // Add single BookingDetails object - model.addAttribute("userName",userSession.getDispayName()); - return bookingsDetails; - } + @GetMapping("/collectionpendingacknowledgementsss") + public BookingDetails viewCollectionpendingAck(Model model, int bookingId) { + BookingDetails bookingsDetails = bookingService.getBookingsById(bookingId); + model.addAttribute("bookingsDetails", bookingsDetails); // Add single BookingDetails object + model.addAttribute("userName", userSession.getDispayName()); + return bookingsDetails; + } @GetMapping("/checkQueue") public ResponseEntity> checkQueue( @@ -1908,6 +1920,5 @@ public class UserAPIController { } - } diff --git a/src/main/java/com/gcc/communityHall/entity/BookingHistory.java b/src/main/java/com/gcc/communityHall/entity/BookingHistory.java index e8c60102..ab077021 100644 --- a/src/main/java/com/gcc/communityHall/entity/BookingHistory.java +++ b/src/main/java/com/gcc/communityHall/entity/BookingHistory.java @@ -44,7 +44,11 @@ public class BookingHistory { @Column(name="end_date") private String endDate; - @ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.EAGER) + /*@ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.EAGER) + @JsonIgnore + private BookingDetails bookingDetails;*/ + + @ManyToOne(fetch = FetchType.EAGER) @JsonIgnore private BookingDetails bookingDetails; diff --git a/src/main/java/com/gcc/communityHall/entity/RefundTransaction.java b/src/main/java/com/gcc/communityHall/entity/RefundTransaction.java index bdcbb9e2..27646beb 100644 --- a/src/main/java/com/gcc/communityHall/entity/RefundTransaction.java +++ b/src/main/java/com/gcc/communityHall/entity/RefundTransaction.java @@ -66,5 +66,18 @@ public class RefundTransaction { } public void setRefundIdentifier(String refundIdentifier) { this.refundIdentifier = refundIdentifier; - } + } + + @Override + public String toString() { + return "RefundTransaction{" + + "refundId=" + refundId + + ", amountRefunded=" + amountRefunded + + ", TransactionId='" + TransactionId + '\'' + + ", refundStatus='" + refundStatus + '\'' + + ", cdate=" + cdate + + ", refundIdentifier='" + refundIdentifier + '\'' + + ", bookingDetails=" + bookingDetails + + '}'; + } } diff --git a/src/main/java/com/gcc/communityHall/paymentService/scheduler/PaymentStatusScheduler.java b/src/main/java/com/gcc/communityHall/paymentService/scheduler/PaymentStatusScheduler.java index 27d6b8f2..d54d27f6 100644 --- a/src/main/java/com/gcc/communityHall/paymentService/scheduler/PaymentStatusScheduler.java +++ b/src/main/java/com/gcc/communityHall/paymentService/scheduler/PaymentStatusScheduler.java @@ -5,6 +5,7 @@ package com.gcc.communityHall.paymentService.scheduler; //package com.gcc.communityHall.paymentService.Scheduler; import com.fasterxml.jackson.databind.ObjectMapper; +import com.gcc.communityHall.entity.BookingCalendar; import com.gcc.communityHall.entity.BookingDetails; import com.gcc.communityHall.entity.Payments; import com.gcc.communityHall.entity.RefundTransaction; @@ -20,6 +21,7 @@ import com.gcc.communityHall.paymentService.repository.TransactionStatusLogRepos import com.gcc.communityHall.paymentService.service.PaymentGatewayServiceImpl; import com.gcc.communityHall.repository.PaymentsRepository; import com.gcc.communityHall.service.BookingService; +import com.gcc.communityHall.service.CalendarService; import com.gcc.communityHall.service.TransactionService; import com.google.gson.Gson; import jakarta.transaction.Transactional; @@ -31,10 +33,7 @@ import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import java.time.LocalDate; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; @Component @EnableScheduling @@ -68,11 +67,14 @@ public class PaymentStatusScheduler { @Autowired private PaymentGatewayServiceImpl paymentGatewayServiceImpl; -// @Scheduled(cron = "0 0 0 * * ?", zone = "Asia/Kolkata") //executed at 12:00 AM - // @Scheduled(fixedRate = 900000) + @Autowired + private CalendarService calendarService; + + // @Scheduled(cron = "0 0 0 * * ?", zone = "Asia/Kolkata") //executed at 12:00 AM + // @Scheduled(fixedRate = 900000) @Scheduled(fixedRate = 30000) public void fetchAndSavePaymentStatus() { - // System.out.println("Fetching Payment Status...At 12:00 AM IST"); + // System.out.println("Fetching Payment Status...At 12:00 AM IST"); System.out.println("Fetching Payment Status...At 15 min Testing"); try { @@ -93,21 +95,21 @@ public class PaymentStatusScheduler { transaction.put("token", ""); transaction.put("reference", ""); - System.out.println("====================================="+ transactionRecord.get("txansaction_id")); + System.out.println("=====================================" + transactionRecord.get("txansaction_id")); System.out.println(merchant); System.out.println(transaction); System.out.println(status); System.out.println(transactionRecord.toString()); System.out.println("======================================"); String bookingDate = transactionRecord.get("booking_date").toString(); - // System.out.println("cdate check"+transactionRecord.get("cdate").toString()); + // System.out.println("cdate check"+transactionRecord.get("cdate").toString()); String cdate = transactionRecord.get("cdate").toString(); if (cdate != null && !cdate.isEmpty()) { String[] dateParts1 = cdate.split(" "); String[] dateParts = dateParts1[0].split("-"); String formattedDate = dateParts[2] + "-" + dateParts[1] + "-" + dateParts[0]; transaction.put("dateTime", formattedDate); - System.out.println("formattedDate"+formattedDate); + System.out.println("formattedDate" + formattedDate); } else { transaction.put("dateTime", ""); } @@ -115,7 +117,7 @@ public class PaymentStatusScheduler { Gson gson = new Gson(); String json = gson.toJson(status); - System.out.println("Hello json "+json); + System.out.println("Hello json " + json); String encryptHxRefund = paymentGatewayService.encryptHxRefund(json); RestTemplate restTemplate = new RestTemplate(); @@ -124,12 +126,12 @@ public class PaymentStatusScheduler { String decryptHxTRefund = paymentGatewayService.decryptHxTRefund(postForEntity.getBody()); Map myObj = new ObjectMapper().readValue(decryptHxTRefund, Map.class); - Map paymentMethod = (Map)myObj.get("paymentMethod"); - Map response = (Map)paymentMethod.get("paymentTransaction"); + Map paymentMethod = (Map) myObj.get("paymentMethod"); + Map response = (Map) paymentMethod.get("paymentTransaction"); System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); System.out.println("hello2" + response); - System.out.println("hello "+myObj); + System.out.println("hello " + myObj); System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); TransactionStatusLog log = new TransactionStatusLog(); @@ -141,7 +143,7 @@ public class PaymentStatusScheduler { log.setStatusMessage(response.get("statusMessage").toString()); log.setStatusCode(response.get("statusCode").toString()); log.setRefundIdentifier(response.get("refundIdentifier").toString()); - // log.setResponse(response.toString()); + // log.setResponse(response.toString()); log.setAmount(response.get("amount").toString()); log.setBalanceAmt(response.get("balanceAmount").toString()); log.setReceivedDate(response.get("dateTime").toString()); @@ -163,21 +165,21 @@ public class PaymentStatusScheduler { Payments payments = paymentsRepository.findByBookingId(Integer.valueOf(String.valueOf(transRes.getBookingId()))); - System.out.println("payments hello"+payments); - if(payments!=null && response.get("statusCode").toString().equals("0300")) { + System.out.println("payments hello" + payments); + if (payments != null && response.get("statusCode").toString().equals("0300")) { // payments.setBookingDetails(payments.getBookingDetails()); payments.setTransactionId(transRes.getTxansactionId()); - payments.setAmountReceived(Double.parseDouble(response.get("amount").toString())); + payments.setAmountReceived(Double.parseDouble(response.get("amount").toString())); payments.setPaymentStatus("Success"); Date date = new Date(payments.getCdate().getTime()); - //paymentsRepository.updatePaymentInfo(payments.getPaymentId(),payments.getTransactionId(),payments.getAmountReceived(),payments.getPaymentStatus(),transRes.getBookingId()); + //paymentsRepository.updatePaymentInfo(payments.getPaymentId(),payments.getTransactionId(),payments.getAmountReceived(),payments.getPaymentStatus(),transRes.getBookingId()); bookingService.updateBookingStatus(transRes.getBookingId(), BookingDetails.BookingStatus.REFUNDED, "Booking Not Confirmed. Amount will be refunded shortly."); - intiateRefund(transRes.getBookingId(),Integer.parseInt(transRes.getUserId())); + intiateRefund(transRes.getBookingId(), Integer.parseInt(transRes.getUserId())); - }else if(response.get("statusCode").toString().equals("0300")){ + } else if (response.get("statusCode").toString().equals("0300")) { payments = new Payments(); @@ -191,13 +193,12 @@ public class PaymentStatusScheduler { //paymentsRepository.insertPaymentinfo(payments.getPaymentId(),payments.getTransactionId(),payments.getAmountReceived(),payments.getPaymentStatus(),transRes.getBookingId(),payments.getCdate() ); bookingService.updateBookingStatus(transRes.getBookingId(), BookingDetails.BookingStatus.REFUNDED, "Booking Not Confirmed. Amount will be refunded shortly."); - intiateRefund(transRes.getBookingId(),Integer.parseInt(transRes.getUserId())); - } - - else{ + intiateRefund(transRes.getBookingId(), Integer.parseInt(transRes.getUserId())); + } else { payments.setBookingDetails(payments.getBookingDetails()); payments.setTransactionId(transRes.getTxansactionId()); - payments.setAmountReceived(Double.parseDouble(response.get("amount")!=null?response.get("amount").toString():"0")); payments.setPaymentStatus("Not Completed"); + payments.setAmountReceived(Double.parseDouble(response.get("amount") != null ? response.get("amount").toString() : "0")); + payments.setPaymentStatus("Not Completed"); payments.setCdate(new Date()); paymentsRepository.save(payments); @@ -205,7 +206,7 @@ public class PaymentStatusScheduler { } - updateRefundInfo(response,log); + updateRefundInfo(response, log); } catch (Exception ex) { System.err.println("Error processing transaction record: " + ex.getMessage()); @@ -221,26 +222,31 @@ public class PaymentStatusScheduler { } - public void updateRefundInfo(Map response,TransactionStatusLog log){ + public void updateRefundInfo(Map response, TransactionStatusLog log) { - if(response.get("refundDdetails") != null ){ + if (response.get("refundDdetails") != null) { - Map refundInfo= (Map) response.get("refundDdetails"); - List> refundDetails = (List>) refundInfo.get("RefundDetails"); - System.out.println("inifcon :"+ refundDetails); - if(refundDetails != null && !refundDetails.isEmpty()){ + Map refundInfo = (Map) response.get("refundDdetails"); + List> refundDetails = (List>) refundInfo.get("RefundDetails"); + System.out.println("inifcon :" + refundDetails); + if (refundDetails != null && !refundDetails.isEmpty()) { RefundResponse refundResponse = new RefundResponse(); - refundResponse.setAmount(response.get("amount")!=null?response.get("amount").toString():""); - refundResponse.setBalaceAmount(response.get("balanceAmount")!=null?response.get("balanceAmount").toString():""); + refundResponse.setAmount(response.get("amount") != null ? response.get("amount").toString() : ""); + refundResponse.setBalaceAmount(response.get("balanceAmount") != null ? response.get("balanceAmount").toString() : ""); refundResponse.setTxansactionId(log.getTransactionId()); - Map mapRef = refundDetails.get(refundDetails.size()-1); + Map mapRef = refundDetails.get(refundDetails.size() - 1); LocalDate df = LocalDate.now(); - try{df =LocalDate.parse(mapRef.get("REF_TXN_DATE").toString());}catch (Exception e){df = LocalDate.now();}; + try { + df = LocalDate.parse(mapRef.get("REF_TXN_DATE").toString()); + } catch (Exception e) { + df = LocalDate.now(); + } + ; refundResponse.setDate(df); - if(mapRef.get("STATUS")!=null && mapRef.get("STATUS").toString().equals("INITIATED")){ + if (mapRef.get("STATUS") != null && mapRef.get("STATUS").toString().equals("INITIATED")) { refundResponse.setStatusCode("0400"); - }else{ + } else { refundResponse.setStatusCode("0399"); } refundResponse.setResponse(refundDetails.toString()); @@ -250,7 +256,7 @@ public class PaymentStatusScheduler { Double amt = Double.parseDouble(response.get("amount").toString()); Double balAmt = Double.parseDouble(response.get("balanceAmount").toString()); - if(amt != balAmt ) { + if (amt != balAmt) { RefundTransaction refundTrans = transactionService.getRefundTrans(saverRefundResponse.getBookingId()); if (refundTrans != null) { @@ -263,31 +269,36 @@ public class PaymentStatusScheduler { transactionService.saveRefundTransaction(refundTrans); } else { refundTrans = new RefundTransaction(); - refundTrans.setAmountRefunded(amt - balAmt); + double refundAmt = amt - balAmt; + System.out.println("refundAmt.."+refundAmt); + refundTrans.setAmountRefunded(refundAmt); refundTrans.setRefundStatus("0400"); refundTrans.setRefundIdentifier(response.get("refundIdentifier").toString()); refundTrans.setCdate(new Date()); refundTrans.setTransactionId(log.getTransactionId()); + BookingDetails bookings = new BookingDetails(); BookingDetails bookingsById = bookingService.getBookingsById(Integer.parseInt(log.getBookingId())); - - refundTrans.setBookingDetails(bookingsById); - transactionService.saveRefundTransaction(refundTrans); - + System.out.println("bookingsById"+bookingsById.getBookingId()); + bookings.setBookingId(bookingsById.getBookingId()); + refundTrans.setBookingDetails(bookings); + System.out.println(refundTrans.toString()); + transactionService.saveRefundTransactionDetails(refundTrans); } - bookingService.updateRefundStatus(saverRefundResponse.getBookingId(),BookingDetails.RefundStatus.COMPLETED); } +// bookingService.updateRefundStatus(saverRefundResponse.getBookingId(), BookingDetails.RefundStatus.COMPLETED); + bookingService.updateRefundStatusScheduler(saverRefundResponse.getBookingId(), BookingDetails.RefundStatus.COMPLETED); + } - saveRefundClientInfo(refundDetails,log.getUserId() ,log.getBookingId(), log.getTransactionId()); + saveRefundClientInfo(refundDetails, log.getUserId(), log.getBookingId(), log.getTransactionId()); } - } } - public String saveRefundClientInfo(List> refundDetail,String userId,String bookingId,String transactionId) { + public String saveRefundClientInfo(List> refundDetail, String userId, String bookingId, String transactionId) { if (refundDetail == null || refundDetail.isEmpty()) { @@ -301,38 +312,39 @@ public class PaymentStatusScheduler { refundClientInfo.setUserId(Integer.parseInt(userId)); refundClientInfo.setBookingId(Integer.parseInt(bookingId)); refundClientInfo.setTransactionId(transactionId); - refundClientInfo.setClntRfndId(refund.get("clnt_rfnd_id")!=null?refund.get("clnt_rfnd_id").toString():""); - refundClientInfo.setArnNo(refund.get("ARN_Number")!=null?refund.get("ARN_Number").toString():""); - refundClientInfo.setGetRefTxnDate(refund.get("REF_TXN_DATE")!=null?refund.get("REF_TXN_DATE").toString():""); - refundClientInfo.setRefTxnAmt(refund.get("REF_TXN_AMT")!=null?refund.get("REF_TXN_AMT").toString():""); - refundClientInfo.setRefTxnId(refund.get("REF_TXN_ID")!=null?refund.get("REF_TXN_ID").toString():""); - refundClientInfo.setStatus(refund.get("STATUS")!=null?refund.get("STATUS").toString():""); - refundClientInfo.setSrno(refund.get("SR_NO")!=null?refund.get("SR_NO").toString():""); + refundClientInfo.setClntRfndId(refund.get("clnt_rfnd_id") != null ? refund.get("clnt_rfnd_id").toString() : ""); + refundClientInfo.setArnNo(refund.get("ARN_Number") != null ? refund.get("ARN_Number").toString() : ""); + refundClientInfo.setGetRefTxnDate(refund.get("REF_TXN_DATE") != null ? refund.get("REF_TXN_DATE").toString() : ""); + refundClientInfo.setRefTxnAmt(refund.get("REF_TXN_AMT") != null ? refund.get("REF_TXN_AMT").toString() : ""); + refundClientInfo.setRefTxnId(refund.get("REF_TXN_ID") != null ? refund.get("REF_TXN_ID").toString() : ""); + refundClientInfo.setStatus(refund.get("STATUS") != null ? refund.get("STATUS").toString() : ""); + refundClientInfo.setSrno(refund.get("SR_NO") != null ? refund.get("SR_NO").toString() : ""); refundClientInfoRepository.save(refundClientInfo); } return "success"; - } + } - @Transactional - public void intiateRefund(int bookingId,int userId) throws Exception { + @Transactional + public void intiateRefund(int bookingId, int userId) throws Exception { + List bc = calendarService.getCalendarByBookingId(bookingId); + if (bc != null && bc.isEmpty()) { String s = paymentGatewayServiceImpl.refundTheAmount(bookingId, userId); - if(s.equals("Refunded")){ - bookingService.updateRefundStatus(bookingId,BookingDetails.RefundStatus.COMPLETED); - - }else - - { - bookingService.updateRefundStatus(bookingId,BookingDetails.RefundStatus.FAILURE); + if (s.equals("Refunded")) { + bookingService.updateRefundStatus(bookingId, BookingDetails.RefundStatus.COMPLETED); } - + } else { + bookingService.updateRefundStatus(bookingId, BookingDetails.RefundStatus.FAILURE); } + } +} + */ diff --git a/src/main/java/com/gcc/communityHall/repository/BookingCalendarRepository.java b/src/main/java/com/gcc/communityHall/repository/BookingCalendarRepository.java index 98a70e45..c71f6607 100644 --- a/src/main/java/com/gcc/communityHall/repository/BookingCalendarRepository.java +++ b/src/main/java/com/gcc/communityHall/repository/BookingCalendarRepository.java @@ -73,4 +73,6 @@ public interface BookingCalendarRepository extends JpaRepository getCalendarByBookingId(int bookingId); } diff --git a/src/main/java/com/gcc/communityHall/repository/BookingDetailsRepository.java b/src/main/java/com/gcc/communityHall/repository/BookingDetailsRepository.java index 6f544ced..530ff4c5 100644 --- a/src/main/java/com/gcc/communityHall/repository/BookingDetailsRepository.java +++ b/src/main/java/com/gcc/communityHall/repository/BookingDetailsRepository.java @@ -337,8 +337,7 @@ public interface BookingDetailsRepository extends JpaRepository> getAllBookingEventsByUserId(Integer userId); //counter diff --git a/src/main/java/com/gcc/communityHall/repository/RefundTransactionRepository.java b/src/main/java/com/gcc/communityHall/repository/RefundTransactionRepository.java index 4916144e..3b5cc641 100644 --- a/src/main/java/com/gcc/communityHall/repository/RefundTransactionRepository.java +++ b/src/main/java/com/gcc/communityHall/repository/RefundTransactionRepository.java @@ -3,8 +3,10 @@ package com.gcc.communityHall.repository; import com.gcc.communityHall.entity.RefundTransaction; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; @Repository public interface RefundTransactionRepository extends JpaRepository { @@ -13,4 +15,15 @@ public interface RefundTransactionRepository extends JpaRepository getBookingCalendarDetails(String fromDate, String toDate, Long bookingId, String hallName); List getBookingsByDateAndHall(String bookingDate, Long hallId); + + BookingDetails updateRefundStatusScheduler(int bookingId, RefundStatus status); } diff --git a/src/main/java/com/gcc/communityHall/service/CalendarService.java b/src/main/java/com/gcc/communityHall/service/CalendarService.java index a00ae38e..ecfd433b 100644 --- a/src/main/java/com/gcc/communityHall/service/CalendarService.java +++ b/src/main/java/com/gcc/communityHall/service/CalendarService.java @@ -10,4 +10,7 @@ public interface CalendarService { List getCalendarByDateAndHallIdAndSlot( String fromDate,String toDate,String startingSlot,String endingSlot, int hallId); + + List getCalendarByBookingId(int bookingId); + } diff --git a/src/main/java/com/gcc/communityHall/service/Impl/BookingServiceImpl.java b/src/main/java/com/gcc/communityHall/service/Impl/BookingServiceImpl.java index 8be32ef8..a8480c87 100644 --- a/src/main/java/com/gcc/communityHall/service/Impl/BookingServiceImpl.java +++ b/src/main/java/com/gcc/communityHall/service/Impl/BookingServiceImpl.java @@ -170,6 +170,7 @@ public class BookingServiceImpl implements BookingService { @Override public BookingDetails getBookingsById(int BookingId) { Optional OPBookingDetails = bookingDetailsRepository.findById(BookingId); + if (OPBookingDetails.isPresent()) { return OPBookingDetails.get(); } @@ -186,7 +187,7 @@ public class BookingServiceImpl implements BookingService { Optional booking = bookingDetailsRepository.findById(bookingId); if (booking.isPresent()) { BookingDetails book = booking.get(); - BookingHistory bookingHistory = new BookingHistory(); + /*BookingHistory bookingHistory = new BookingHistory(); bookingHistory.setBookingDetails(book); bookingHistory.setStartDate(book.getStartDate()); bookingHistory.setEndDate(book.getEndDate()); @@ -194,7 +195,8 @@ public class BookingServiceImpl implements BookingService { bookingHistory.setComments(book.getComments()); bookingHistory.setCdate(new Date()); bookingHistory.setRefundStatus(book.getRefundStatus()); - bookingHistoryRepository.save(bookingHistory); + System.out.println("bookingHistory.."+bookingHistory); + bookingHistoryRepository.save(bookingHistory);*/ book.setBookingStatus(status); book.setComments(comments); @@ -365,50 +367,50 @@ public class BookingServiceImpl implements BookingService { @Transactional public String processBookingStatusAndSendMessages(BookingDetails bookingDetails) { - try{ - String reason = bookingDetails.getReason(); - ReasonMaster reasonDetails = reasonMasterRepository.findByReason(reason); - String reasonCode = (reasonDetails != null && reasonDetails.getReasoncode() != null) ? reasonDetails.getReasoncode() : ""; + try { + String reason = bookingDetails.getReason(); + ReasonMaster reasonDetails = reasonMasterRepository.findByReason(reason); + String reasonCode = (reasonDetails != null && reasonDetails.getReasoncode() != null) ? reasonDetails.getReasoncode() : ""; - String bookingconfirmationmsg, urlString, whatsupmsg; + String bookingconfirmationmsg, urlString, whatsupmsg; - if (reasonCode.equals("CGE") || reasonCode.equals("CAO") || reasonCode.equals("SGE")) { - updateBookingStatusById(bookingDetails.getBookingId(), BookingDetails.BookingStatus.WAITING_FOR_NOC, "Waiting For NOC Documents"); + if (reasonCode.equals("CGE") || reasonCode.equals("CAO") || reasonCode.equals("SGE")) { + updateBookingStatusById(bookingDetails.getBookingId(), BookingDetails.BookingStatus.WAITING_FOR_NOC, "Waiting For NOC Documents"); - bookingconfirmationmsg = "Your booking ID " + bookingDetails.getBookingId() + " on " + bookingDetails.getBookingDate() + " has been confirmed successfully. Thanks for using GCC Community Hall Booking System."; + bookingconfirmationmsg = "Your booking ID " + bookingDetails.getBookingId() + " on " + bookingDetails.getBookingDate() + " has been confirmed successfully. Thanks for using GCC Community Hall Booking System."; - urlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + bookingDetails.getUsers().getMobileNo() + - "&from=GCCCRP&body=" + bookingconfirmationmsg + "&entityid=1401572690000011081&templateid=1407172346459428987"; + urlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + bookingDetails.getUsers().getMobileNo() + + "&from=GCCCRP&body=" + bookingconfirmationmsg + "&entityid=1401572690000011081&templateid=1407172346459428987"; - whatsupmsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + - 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."; + whatsupmsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + + bookingDetails.getUsers().getMobileNo() + + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+booking+with+ID+" + + bookingDetails.getBookingId() + "+on+" + bookingDetails.getBookingDate() + + "+has+been+successfully+confirmed.+%0AThanks+for+using+GCC+Community+Hall+Booking+System."; - whatsappMsgServiceImpl.sendMsg(whatsupmsg); - whatsappMsgServiceImpl.sendSMS(urlString); - return "Waiting For NOC Documents"; + whatsappMsgServiceImpl.sendMsg(whatsupmsg); + whatsappMsgServiceImpl.sendSMS(urlString); + return "Waiting For NOC Documents"; - } else { - updateBookingStatusById(bookingDetails.getBookingId(), BookingDetails.BookingStatus.APPROVED, "Booking Confirmed Successfully"); + } else { + updateBookingStatusById(bookingDetails.getBookingId(), BookingDetails.BookingStatus.APPROVED, "Booking Confirmed Successfully"); - bookingconfirmationmsg = "Your booking ID " + bookingDetails.getBookingId() + " on " + bookingDetails.getStartDate() + " has been confirmed successfully. Thanks for using GCC Community Hall Booking System."; + bookingconfirmationmsg = "Your booking ID " + bookingDetails.getBookingId() + " on " + bookingDetails.getStartDate() + " has been confirmed successfully. Thanks for using GCC Community Hall Booking System."; - urlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + bookingDetails.getUsers().getMobileNo() + - "&from=GCCCRP&body=" + bookingconfirmationmsg + "&entityid=1401572690000011081&templateid=1407172346459428987"; + urlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to=" + bookingDetails.getUsers().getMobileNo() + + "&from=GCCCRP&body=" + bookingconfirmationmsg + "&entityid=1401572690000011081&templateid=1407172346459428987"; - whatsupmsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + - 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."; + whatsupmsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to=" + + bookingDetails.getUsers().getMobileNo() + + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+booking+with+ID+" + + bookingDetails.getBookingId() + "+on+" + bookingDetails.getStartDate() + + "+has+been+successfully+confirmed.+%0AThanks+for+using+GCC+Community+Hall+Booking+System."; - whatsappMsgServiceImpl.sendMsg(whatsupmsg); - whatsappMsgServiceImpl.sendSMS(urlString); - return "Booking confirmed successfully"; - } - }catch (Exception e){ + whatsappMsgServiceImpl.sendMsg(whatsupmsg); + whatsappMsgServiceImpl.sendSMS(urlString); + return "Booking confirmed successfully"; + } + } catch (Exception e) { e.printStackTrace(); return "error"; } @@ -979,6 +981,9 @@ public class BookingServiceImpl implements BookingService { bd.setBookingDetails(bookingDetails); // Set the associated booking details bookingDetails.setBookingStatus(BookingStatus.WAITING_FOR_NOC_APPROVAL); bookingDetails.setComments("Waiting for Admin Approval"); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + String formattedDate = LocalDateTime.now().format(formatter); + bookingDetails.setUpdatedDate(formattedDate); // Save the file to the server try (FileOutputStream fos = new FileOutputStream(filePath)) { @@ -1603,17 +1608,18 @@ public class BookingServiceImpl implements BookingService { String adminname = (String) session.getAttribute("usertype"); BookingDetails book = booking.get(); book.setRefundStatus(status); -// BookingHistory bookingHistory=new BookingHistory(); -// bookingHistory.setStartDate(book.getStartDate()); -// bookingHistory.setEndDate(book.getEndDate()); -// bookingHistory.setComments(book.getComments()); -// bookingHistory.setBookingDetails(book); -// bookingHistory.setBookingStatus(book.getBookingStatus()); -// bookingHistory.setUpdatedBy(adminname); -// bookingHistory.setCdate(new Date()); -// bookingHistory.setRefundStatus(book.getRefundStatus()); + BookingHistory bookingHistory = new BookingHistory(); + bookingHistory.setStartDate(book.getStartDate()); + bookingHistory.setEndDate(book.getEndDate()); + bookingHistory.setComments(book.getComments()); + bookingHistory.setBookingDetails(book); + bookingHistory.setBookingStatus(book.getBookingStatus()); + bookingHistory.setUpdatedBy(adminname); + bookingHistory.setCdate(new Date()); + bookingHistory.setRefundStatus(book.getRefundStatus()); + bookingHistoryRepository.save(bookingHistory); book.setComments("Refund status Updated to:-" + status); -// bookingHistoryRepository.save(bookingHistory); + BookingDetails bookings = bookingDetailsRepository.save(book); return bookings; } @@ -1778,6 +1784,9 @@ public class BookingServiceImpl implements BookingService { Optional book = bookingDetailsRepository.findById(bookingId); BookingDetails bookingDetails = book.get(); bookingDetails.setScheduleCount(bookingDetails.getScheduleCount() + 1); + if (bookingDetails.getReason().equals("Commercial")) { + bookingDetails.setBookingStatus(BookingStatus.WAITING_FOR_NOC); + } //Updating Bookinghistory startDate and End Date BookingHistory bookingHistory = new BookingHistory(); bookingHistory.setStartDate(bookingDetails.getStartDate()); @@ -1791,6 +1800,9 @@ public class BookingServiceImpl implements BookingService { bookingDetails.setEndDate(endDate); bookingHistory.setRefundStatus(bookingDetails.getRefundStatus()); bookingDetails.setComments("slots Resheduled the Dates"); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + String formattedDate = LocalDateTime.now().format(formatter); + bookingDetails.setUpdatedDate(formattedDate); bookingDetailsRepository.save(bookingDetails); bookingHistoryRepository.save(bookingHistory); } @@ -2396,5 +2408,32 @@ public class BookingServiceImpl implements BookingService { return bookingDetailsRepository.findByBookingDateAndHallId(date, hallId); } + @Override + @Transactional + public BookingDetails updateRefundStatusScheduler(int bookingId, RefundStatus status) { + Optional booking = bookingDetailsRepository.findById(bookingId); + if (booking.isPresent()) { + String adminname = "Refund Scheduler"; + BookingDetails book = booking.get(); + book.setRefundStatus(status); + book.setComments("Refund status Updated to:-" + status); + BookingDetails bookings = bookingDetailsRepository.save(book); + + BookingHistory bookingHistory = new BookingHistory(); + bookingHistory.setStartDate(book.getStartDate()); + bookingHistory.setEndDate(book.getEndDate()); + bookingHistory.setComments(book.getComments()); + bookingHistory.setBookingDetails(book); + bookingHistory.setBookingStatus(book.getBookingStatus()); + bookingHistory.setUpdatedBy(adminname); + bookingHistory.setCdate(new Date()); + bookingHistory.setRefundStatus(book.getRefundStatus()); + bookingHistoryRepository.save(bookingHistory); + + return bookings; + } + return null; + } + } diff --git a/src/main/java/com/gcc/communityHall/service/Impl/CalendarServiceImpl.java b/src/main/java/com/gcc/communityHall/service/Impl/CalendarServiceImpl.java index 09efe1d5..da46d32a 100644 --- a/src/main/java/com/gcc/communityHall/service/Impl/CalendarServiceImpl.java +++ b/src/main/java/com/gcc/communityHall/service/Impl/CalendarServiceImpl.java @@ -30,4 +30,12 @@ public class CalendarServiceImpl implements CalendarService { } } + + @Override + public List getCalendarByBookingId(int bookingId) { + if(bookingId!=0){ + return bookingCalendarRepository.getCalendarByBookingId(bookingId); + } + return null; + } } \ No newline at end of file diff --git a/src/main/java/com/gcc/communityHall/service/Impl/TransactionServiceImpl.java b/src/main/java/com/gcc/communityHall/service/Impl/TransactionServiceImpl.java index cc316115..c48e2589 100644 --- a/src/main/java/com/gcc/communityHall/service/Impl/TransactionServiceImpl.java +++ b/src/main/java/com/gcc/communityHall/service/Impl/TransactionServiceImpl.java @@ -3,6 +3,7 @@ package com.gcc.communityHall.service.Impl; import com.gcc.communityHall.entity.RefundTransaction; import com.gcc.communityHall.repository.RefundTransactionRepository; import com.gcc.communityHall.service.TransactionService; +import jakarta.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -21,4 +22,19 @@ public class TransactionServiceImpl implements TransactionService { public RefundTransaction saveRefundTransaction(RefundTransaction refundTransaction) { return refundTransactionRepository.save(refundTransaction); } + + @Transactional + @Override + public void saveRefundTransactionDetails(RefundTransaction refundTransaction) { + refundTransactionRepository.insertRefundTransaction( + refundTransaction.getTransactionId(), + refundTransaction.getAmountRefunded(), + refundTransaction.getCdate(), + refundTransaction.getRefundStatus(), + refundTransaction.getBookingDetails().getBookingId(), + refundTransaction.getRefundIdentifier() + ); +// return refundTransaction; // returning the same object after manual insert + } + } diff --git a/src/main/java/com/gcc/communityHall/service/TransactionService.java b/src/main/java/com/gcc/communityHall/service/TransactionService.java index 9eb4d32f..03e6357a 100644 --- a/src/main/java/com/gcc/communityHall/service/TransactionService.java +++ b/src/main/java/com/gcc/communityHall/service/TransactionService.java @@ -7,4 +7,6 @@ public interface TransactionService { RefundTransaction getRefundTrans(int bookingId); RefundTransaction saveRefundTransaction(RefundTransaction refundTransaction); + + void saveRefundTransactionDetails(RefundTransaction refundTrans); } diff --git a/src/main/resources/templates/admin/reports.html b/src/main/resources/templates/admin/reports.html index 14813d86..fff88ecb 100644 --- a/src/main/resources/templates/admin/reports.html +++ b/src/main/resources/templates/admin/reports.html @@ -6,1923 +6,2042 @@ - - - - -
- - - - + + + + // Display booking documents + function showReasonWithDocument(reasonData, list) { + var reasonDocumentData = reasonData.reasonDocumentMasterList; + var bookingDocumentsList = list.bookingDocumentsList; + + const reasonFieldsContainer = $('#documents'); + reasonFieldsContainer.empty(); + + // Create a responsive table container + var tableResponsiveDiv = $('
').addClass('table-responsive').css({'width': '770px', 'border': 'black'}); + + // Create the table with Bootstrap classes and custom styles + var table = $('').addClass('table table-bordered table-striped table-vcenter js-dataTable-responsive').css({ + 'width': '100%', + 'height': 'auto', + 'border': '1px solid black' + }); + + // Create the table header (thead) + var thead = $('').appendTo(table); + var headerRow = $('').appendTo(thead); + $('').appendTo(thead); + $('').appendTo(table); + + // Iterate through the documents list and populate rows + for (var i = 0; i < bookingDocumentsList.length; i++) { + (function (index) { + var row = $('').appendTo(tbody); + $('' + // Added tag + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + ''; // Close tag + + // Append the row to the table body + $("#bookingTableBody").append(row); + }); + $('#viewbookingDetailsdetails').modal('show'); + }, + error: function (xhr, status, error) { + console.error(xhr.responseText); + // Handle error here + } + }); + } + + function viewbookingDetailsbasedonzone(zone) { + $.ajax({ + type: "GET", + url: '/communityhall/admin/api/bookingdetailsByzone', + data: {'zone': zone}, + success: function (response) { + // console.log(response); + + // Clear existing table data and destroy DataTable instance if it exists + var table = $('#bookinglistdataTablebyzone').DataTable(); + if (table) { + table.clear().destroy(); + } + + // Populate table with new data + var tableBody = $("#bookingTableBodybyzone"); + tableBody.empty(); // Clear the table body + + $.each(response, function (index, booking) { + var row = '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + ''; + + tableBody.append(row); + }); + + // Initialize DataTable + $('#bookinglistdataTablebyzone').DataTable({ + "paging": true, + "searching": true, + "ordering": true, + "info": true + }); + + // Show the modal + $('#viewbookingDetailsbyzone').modal('show'); + }, + error: function (xhr, status, error) { + console.error(xhr.responseText); + // Handle error here + } + }); + } + + document.addEventListener('DOMContentLoaded', function () { + fetchData(); + + restoreSelectedValues(); + document.getElementById('request').addEventListener('change', function () { + myRequest(); // Handle request change + }); + + document.getElementById('zone1').addEventListener('change', function () { + updateDivisions(); + }); + document.getElementById('division1').addEventListener('change', function () { + updateHalls(); + }); + }); + + function fetchData() { + fetch('/communityhall/user/api/getZonehalls') // Replace with your actual API endpoint + .then(response => response.json()) + .then(data => { + populateDropdowns(data); + restoreSelectedValues(); + }) + .catch(error => console.error('Error fetching data:', error)); + } + + function populateDropdowns(data) { + const zoneDropdown = document.getElementById('zone1'); + const divisionDropdown = document.getElementById('division1'); + const hallDropdown = document.getElementById('hall1'); + + const zones = new Set(); + const divisionsByZone = {}; + const hallsByDivision = {}; + + data.forEach(item => { + zones.add(item.zone); + if (!divisionsByZone[item.zone]) { + divisionsByZone[item.zone] = []; + } + if (!divisionsByZone[item.zone].includes(item.division)) { + divisionsByZone[item.zone].push(item.division); + } + if (!hallsByDivision[item.division]) { + hallsByDivision[item.division] = []; + } + hallsByDivision[item.division].push({hallName: item.hall_name, hallId: item.hall_id}); + }); + + // Populate zones + zones.forEach(zone => { + const option = document.createElement('option'); + option.value = zone; + option.textContent = zone; + zoneDropdown.appendChild(option); + }); + + zoneDropdown.dataset.divisionsByZone = JSON.stringify(divisionsByZone); + divisionDropdown.dataset.hallsByDivision = JSON.stringify(hallsByDivision); + + // Initialize divisions and halls + updateDivisions(); + } + + function updateDivisions() { + const zoneDropdown = document.getElementById('zone1'); + const selectedZone = zoneDropdown.value; + const divisionsByZone = JSON.parse(zoneDropdown.dataset.divisionsByZone || '{}'); + + const divisionDropdown = document.getElementById('division1'); + divisionDropdown.innerHTML = ''; + + const allOption = document.createElement('option'); + allOption.value = ''; + allOption.textContent = '--Select Division--'; + divisionDropdown.appendChild(allOption); + + if (selectedZone === '') { + document.getElementById('divisionContainer').classList.add('hidden'); + } else { + document.getElementById('divisionContainer').classList.remove('hidden'); + (divisionsByZone[selectedZone] || []).forEach(division => { + const option = document.createElement('option'); + option.value = division; + option.textContent = division; + divisionDropdown.appendChild(option); + }); + updateHalls(); + } + } + + function updateHalls() { + const divisionDropdown = document.getElementById('division1'); + const selectedDivision = divisionDropdown.value; + const hallsByDivision = JSON.parse(divisionDropdown.dataset.hallsByDivision || '{}'); + + const hallDropdown = document.getElementById('hall1'); + hallDropdown.innerHTML = ''; + + const allOption = document.createElement('option'); + allOption.value = ''; + allOption.textContent = '--Select Hall--'; + hallDropdown.appendChild(allOption); + + if (selectedDivision === '') { + document.getElementById('hallContainer').classList.add('hidden'); + } else { + document.getElementById('hallContainer').classList.remove('hidden'); + (hallsByDivision[selectedDivision] || []).forEach(hall => { + const option = document.createElement('option'); + option.value = hall.hallId; + option.textContent = hall.hallName; + hallDropdown.appendChild(option); + }); + } + } + + function restoreSelectedValues() { + const selectedZone = localStorage.getItem('selectedZone') || ''; + const selectedDivision = localStorage.getItem('selectedDivision') || ''; + const selectedHall = localStorage.getItem('selectedHall') || ''; + + const zoneDropdown = document.getElementById('zone1'); + const divisionDropdown = document.getElementById('division1'); + const hallDropdown = document.getElementById('hall1'); + + zoneDropdown.value = selectedZone; + updateDivisions(); // Populate divisions based on selected zone + + // Make sure to set the division and hall values after the dropdowns are populated + divisionDropdown.value = selectedDivision; + updateHalls(); // Populate halls based on selected division + + hallDropdown.value = selectedHall; + } + + // Store selected values before form submission + function storeSelectedValues() { + const zoneDropdown = document.getElementById('zone1'); + const divisionDropdown = document.getElementById('division1'); + const hallDropdown = document.getElementById('hall1'); + + localStorage.setItem('selectedZone', zoneDropdown.value); + localStorage.setItem('selectedDivision', divisionDropdown.value); + localStorage.setItem('selectedHall', hallDropdown.value); + } + + document.getElementById('myForm').addEventListener('submit', function () { + storeSelectedValues(); + }); + + \ No newline at end of file diff --git a/src/main/resources/templates/user/calculatehallamount.html b/src/main/resources/templates/user/calculatehallamount.html index 5cb5cb8a..4f5106e1 100644 --- a/src/main/resources/templates/user/calculatehallamount.html +++ b/src/main/resources/templates/user/calculatehallamount.html @@ -503,8 +503,9 @@ var startPeriod = $('#startPeriodDropdown').val(); var endPeriod = $('#endPeriodDropdown').val(); var reasonForBooking = $('#reasonforBooking').val(); + // console.log("reasonForBooking="+reasonForBooking); - if (reasonforBooking === '') { + if (reasonForBooking.trim() === '') { $('#reasonforBooking')[0].setCustomValidity('Please select reason for booking.'); $('#reasonforBooking')[0].reportValidity(); return; @@ -514,6 +515,7 @@ // Validate input fields if (isNaN(numDays) || numDays < 1 || numDays > 7) { + console.log("num of days") $('#numDaysCount')[0].setCustomValidity('Please select a valid number of days.'); $('#numDaysCount')[0].reportValidity(); return; diff --git a/src/main/resources/templates/user/viewhistory.html b/src/main/resources/templates/user/viewhistory.html index 043eb204..877dd38c 100644 --- a/src/main/resources/templates/user/viewhistory.html +++ b/src/main/resources/templates/user/viewhistory.html @@ -7,620 +7,621 @@ - -
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - -
-
- - - - -
- -
-
-
- - -
-
- - - -
-
-
Hall Booking Details
- + +
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
- -
-
-
').attr('colspan', '3').text('Document Details').css({ + 'color': 'black', + 'background-color': '#f2f2f2', + 'padding': '0.45rem 0.45rem' + }).appendTo(headerRow); + + // Create header row for columns + var columnHeadersRow = $('
').text('S.No').appendTo(columnHeadersRow); + $('').text('Required Info').appendTo(columnHeadersRow); + $('').text('Required Documents').appendTo(columnHeadersRow); + + // Create the table body (tbody) + var tbody = $('
').text(index + 1).appendTo(row); + $('').text(reasonDocumentData[index].fieldName + ': ' + bookingDocumentsList[index].name).appendTo(row); + + // Create a link to view document image + var viewLink = $('').attr('href', 'javascript:void(0)').text(reasonDocumentData[index].docFieldName).on('click', function () { + showDocumentImage(bookingDocumentsList[index].bookingDocUrl); + }); + $('').append(viewLink).appendTo(row); + })(i); + } + + // Append table to the responsive container + tableResponsiveDiv.append(table); + + // Append table to the container in the DOM + reasonFieldsContainer.append(tableResponsiveDiv); + } + + + function showDocumentImage(fileURL) { + //console.log(fileURL); + openFileModal(fileURL); + } + + // Event delegation for dynamically added elements + $(document).on('click', '.view-document', function () { + const fileURL = $(this).data('url'); + openFileModal(fileURL); + }); + + function openFileModal(fileURL) { + $('#filePreview').attr('src', fileURL); + $('#fileModal').modal('show'); + } + + function viewbookingDetails(userId) { + $.ajax({ + type: "GET", + url: '/communityhall/admin/api/bookingdetailsByuserId', + data: {'userId': userId}, + success: function (response) { + // console.log(response); + $("#bookingTableBody").empty(); // Ensure bookingTableBody is the correct ID of the table body + $.each(response, function (index, booking) { + // Create table row with the data from response + var row = '
' + (index + 1) + '' + booking.bookingId + '' + booking.bookingDate + '' + booking.startDate + '' + booking.endDate + '' + booking.startingSlot + '' + booking.endingSlot + '' + booking.reason + '' + booking.noOfDays + '' + booking.bookingStatus + '' + booking.hallAmount + '' + booking.amountReceived + '
' + (index + 1) + '' + booking.bookingId + '' + booking.bookingDate + '' + booking.startDate + '' + booking.endDate + '' + booking.startingSlot + '' + booking.endingSlot + '' + booking.reason + '' + booking.noOfDays + '' + booking.bookingStatus + '' + booking.hallAmount + '' + booking.amountReceived + '
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + +
S.NoBooking IdBooking dateHall NameStarting DateEnding DateStarting PeriodEnding PeriodReason for bookingBooking StatusPayment StatusEvent StatusActionView
- - - - + + +
+
+ + + + +
+ +
+
+
+ + +
+
+ + + +
+
+
Hall Booking Details
+ +
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + - - - -
S.NoBooking IdBooking dateHall NameStarting DateEnding DateStarting PeriodEnding PeriodReason for bookingBooking StatusPayment StatusEvent StatusActionView
+ + + + Current Event @@ -631,957 +632,1068 @@ Govt Event - + Refund Completed Event - + User Canceled Event - + GCC Rejected Event - + GCC Blocked Event - + Waiting For NOC Document - + Waiting For Admin Approval - + -

- +

+ Cancel + style="cursor: pointer;" + th:onclick="cancelBooking([[${booking.booking_id}]], [[${booking.mobile_no}]], [[${booking.booking_type}]])">Cancel Booking - -

-

- + +

+

+ Upload + style="cursor: pointer;" + data-bs-toggle="modal" + data-bs-target="#uploadNocModal" + th:attr="data-booking-id=${booking.booking_id}">Upload NOC - + - + Cancel + style="cursor: pointer;" + th:onclick="cancelBooking([[${booking.booking_id}]], [[${booking.mobile_no}]], [[${booking.booking_type}]])">Cancel Booking - -

- -

- + + + +

+ +

+ Cancel + style="cursor: pointer;" + th:onclick="cancelBooking([[${booking.booking_id}]], [[${booking.mobile_no}]], [[${booking.booking_type}]])">Cancel Booking - -

- - -

- - + +

+ + +

+ + Cancel + style="cursor: pointer;" + th:onclick="cancelBooking([[${booking.booking_id}]], [[${booking.mobile_no}]], [[${booking.booking_type}]])">Cancel Booking - - -

-

- - --No Action-- - -

-

- + + +

+

+ + --No Action-- + +

+

+ Cancel + style="cursor: pointer;" + th:onclick="cancelBooking([[${booking.booking_id}]], [[${booking.mobile_no}]], [[${booking.booking_type}]])">Cancel Booking - - + + Reschedule Booking - -

+ + + Reschedule + Booking + -
- - View - - -
-
-
- -
- - - -
-
-
-
-
+
+ + + + + + + +
+ + + - - - - - - - - - - - - + + + + + + + + + + + + +
+ + + + + +
+ + + + + + + + + - - - - - - - + // Toggle Chat Box + function toggleChat() { + const chatBox = document.getElementById('chat-box'); + chatBox.style.display = (chatBox.style.display === 'block') ? 'none' : 'block'; + } + + // Send Message + function sendMessage() { + const userInput = document.getElementById('userInput'); + const message = userInput.value.trim(); + + if (message) { + // Create message element + const chatBody = document.getElementById('chat-body'); + const userMessage = document.createElement('div'); + userMessage.className = 'user-message'; + userMessage.textContent = message; + + chatBody.appendChild(userMessage); + chatBody.scrollTop = chatBody.scrollHeight; // Auto-scroll to bottom + + // Send message to the server (Spring Boot API) + fetch('/communityhall/admin/api/send', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({message}), + }) + .then(response => response.json()) + .then(data => { + // Add response message to chat + const responseMessage = document.createElement('div'); + responseMessage.className = 'bot-message'; + responseMessage.textContent = data.response; + + chatBody.appendChild(responseMessage); + chatBody.scrollTop = chatBody.scrollHeight; + }); + + userInput.value = ''; // Clear input field + } + } + + - - - + + + \ No newline at end of file