Browse Source

Reason master restriction and amount configuration changed

master
KaNi-04 4 months ago
parent
commit
dd132f0fa8
  1. 682
      src/main/java/com/gcc/communityHall/controller/AdminAPIController.java
  2. 806
      src/main/java/com/gcc/communityHall/controller/OfficerAPIController.java
  3. 207
      src/main/java/com/gcc/communityHall/entity/HallRequestDetails.java
  4. 45
      src/main/java/com/gcc/communityHall/entity/ReasonMaster.java
  5. 11
      src/main/java/com/gcc/communityHall/exception/PaymentRefundSlotOccupiedException.java
  6. 778
      src/main/java/com/gcc/communityHall/paymentService/controller/PaymentController.java
  7. 84
      src/main/java/com/gcc/communityHall/paymentService/repository/TransactionResponseRepository.java
  8. 39
      src/main/java/com/gcc/communityHall/repository/BookingDetailsRepository.java
  9. 39
      src/main/java/com/gcc/communityHall/repository/HallRequestDetailsRepository.java
  10. 23
      src/main/java/com/gcc/communityHall/repository/PaymentsRepository.java
  11. 5
      src/main/java/com/gcc/communityHall/repository/ReasonMasterRepository.java
  12. 268
      src/main/java/com/gcc/communityHall/service/BookingService.java
  13. 374
      src/main/java/com/gcc/communityHall/service/Impl/BookingServiceImpl.java
  14. 63
      src/main/java/com/gcc/communityHall/service/Impl/ReasonMasterImpl.java
  15. 10
      src/main/java/com/gcc/communityHall/service/ReasonMasterService.java
  16. 2
      src/main/resources/templates/user/hallbookingform.html

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

@ -97,10 +97,7 @@ import lombok.AllArgsConstructor;
//@RestController
//@RequestMapping("/admin/api")
@Tag(
name = "CRUD REST APIs for Admin in CommunityHall",
description = "CRUD REST APIs in CommunityHall to CREATE, UPDATE, FETCH AND DELETE Booking details"
)
@Tag(name = "CRUD REST APIs for Admin in CommunityHall", description = "CRUD REST APIs in CommunityHall to CREATE, UPDATE, FETCH AND DELETE Booking details")
@RestController
@RequestMapping("/victoriahallbooking/admin/api")
@AllArgsConstructor
@ -168,32 +165,10 @@ public class AdminAPIController {
@Autowired
private ApplicationLogsRepository applicationLogsRepository;
@Operation(
summary = "Update HallDetails REST API",
description = "REST API to update the Hall Details"
)
@Operation(summary = "Update HallDetails REST API", description = "REST API to update the Hall Details")
@ApiResponses({
@ApiResponse(
responseCode = "200",
description = "HTTP Status UPDATED",
content = @Content(
mediaType = "text/plain",
schema = @Schema(implementation = HallDetails.class),
examples = @ExampleObject(value = "Hall details updated successfully")
)
),
@ApiResponse(
responseCode = "500",
description = "HTTP Status Internal Server Error",
content = @Content(
mediaType = "application/json",
schema = @Schema(implementation = ErrorResponseDto.class),
examples = @ExampleObject(
name = "Internal Server Error Example",
value = "{ \"path\": \"/updateHallDetails\", \"status\": 500, \"error\": \"Internal Server Error\", \"timestamp\": \"2024-06-22T05:47:04.347+00:00\" }"
)
)
)
@ApiResponse(responseCode = "200", description = "HTTP Status UPDATED", content = @Content(mediaType = "text/plain", schema = @Schema(implementation = HallDetails.class), examples = @ExampleObject(value = "Hall details updated successfully"))),
@ApiResponse(responseCode = "500", description = "HTTP Status Internal Server Error", content = @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponseDto.class), examples = @ExampleObject(name = "Internal Server Error Example", value = "{ \"path\": \"/updateHallDetails\", \"status\": 500, \"error\": \"Internal Server Error\", \"timestamp\": \"2024-06-22T05:47:04.347+00:00\" }")))
})
@PostMapping("/updateHallDetails")
public ResponseEntity<String> updateHallInfo(
@ -270,43 +245,18 @@ public class AdminAPIController {
return ResponseEntity.ok("Success");
}
@Operation(
summary = "Update Settlement Status REST API",
description = "REST API to update the Settlement Status to INITIATED"
)
@Operation(summary = "Update Settlement Status REST API", description = "REST API to update the Settlement Status to INITIATED")
@ApiResponses({
@ApiResponse(
responseCode = "200",
description = "HTTP Status UPDATED",
content = @Content(
mediaType = "application/json",
schema = @Schema(implementation = Settlement.class),
examples = @ExampleObject(
name = "Settlement Example",
value = "{\"settlementId\": Id, \"Refundstatus\": \"INITIATED\", \"comments\": \"Settlement initiated successfully\"}"
)
)
),
@ApiResponse(
responseCode = "500",
description = "HTTP Status Internal Server Error",
content = @Content(
mediaType = "application/json",
schema = @Schema(implementation = ErrorResponseDto.class),
examples = @ExampleObject(
name = "Internal Server Error Example",
value = "{ \"path\": \"/updateInitiatedSettlementStatus/{settlementId}\", \"status\": 500, \"error\": \"Internal Server Error\", \"timestamp\": \"2024-06-22T05:47:04.347+00:00\" }"
)
)
)
@ApiResponse(responseCode = "200", description = "HTTP Status UPDATED", content = @Content(mediaType = "application/json", schema = @Schema(implementation = Settlement.class), examples = @ExampleObject(name = "Settlement Example", value = "{\"settlementId\": Id, \"Refundstatus\": \"INITIATED\", \"comments\": \"Settlement initiated successfully\"}"))),
@ApiResponse(responseCode = "500", description = "HTTP Status Internal Server Error", content = @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponseDto.class), examples = @ExampleObject(name = "Internal Server Error Example", value = "{ \"path\": \"/updateInitiatedSettlementStatus/{settlementId}\", \"status\": 500, \"error\": \"Internal Server Error\", \"timestamp\": \"2024-06-22T05:47:04.347+00:00\" }")))
})
@PostMapping("/updateInitiatedSettlementStatus/{settlementId}")
public ResponseEntity<Settlement> updateInitiatedSettlementStatus(
@PathVariable("settlementId") int settlementId,
@RequestParam("status") BookingDetails.RefundStatus status,
@RequestParam("comments") String comments) {
Settlement updateInitialiseSettlement = settlementService.updateSettlementStatus(settlementId, status, comments);
Settlement updateInitialiseSettlement = settlementService.updateSettlementStatus(settlementId, status,
comments);
String adminname = (String) session.getAttribute("usertype");
Integer loginid = (Integer) session.getAttribute("id");
ApplicationLogs logs = new ApplicationLogs();
@ -330,27 +280,11 @@ public class AdminAPIController {
}
}
@Operation(
summary = "HallDetails by HallId REST API",
description = "REST API to Retrieving the Hall Details by hallId"
)
@Operation(summary = "HallDetails by HallId REST API", description = "REST API to Retrieving the Hall Details by hallId")
@ApiResponses({
@ApiResponse(
responseCode = "200",
description = "HTTP Status OK",
content = @Content(
mediaType = "application/json",
schema = @Schema(implementation = HallDetails.class)
)
),
@ApiResponse(
responseCode = "400",
description = "Bad Request"
),
@ApiResponse(
responseCode = "404",
description = "Not Found"
)
@ApiResponse(responseCode = "200", description = "HTTP Status OK", content = @Content(mediaType = "application/json", schema = @Schema(implementation = HallDetails.class))),
@ApiResponse(responseCode = "400", description = "Bad Request"),
@ApiResponse(responseCode = "404", description = "Not Found")
})
@GetMapping("/getHallDetails/{hallId}")
public ResponseEntity<HallDetails> getHallDetails(@PathVariable String hallId) {
@ -362,7 +296,7 @@ public class AdminAPIController {
}
HallDetails hallDetails = hallDetailsRepository.findHallDetailsById(id);
//System.out.println(hallDetails.isActive());
// System.out.println(hallDetails.isActive());
if (hallDetails != null) {
return ResponseEntity.ok(hallDetails);
} else {
@ -370,10 +304,7 @@ public class AdminAPIController {
}
}
@Operation(
summary = "Saving the DiscountRange REST API",
description = "REST API to Saving the Discount Range for usertypes"
)
@Operation(summary = "Saving the DiscountRange REST API", description = "REST API to Saving the Discount Range for usertypes")
@PostMapping("/savediscountrange")
public String saveDiscountrange(
@RequestParam String userType,
@ -427,12 +358,10 @@ public class AdminAPIController {
return "success";
}
@Operation(
summary = " Update the DiscountRange REST API",
description = "REST API to Updating the Discount Range for usertypes"
)
@Operation(summary = " Update the DiscountRange REST API", description = "REST API to Updating the Discount Range for usertypes")
@PutMapping("/updateById/{id}")
public String updateDiscountRangeById(@PathVariable int id, @RequestParam float discountRange, HttpSession session) {
public String updateDiscountRangeById(@PathVariable int id, @RequestParam float discountRange,
HttpSession session) {
String adminname = (String) session.getAttribute("usertype");
Optional<DiscountRange> existingDiscount = discountRangeRepo.findById(id);
if (existingDiscount.isPresent()) {
@ -462,11 +391,7 @@ public class AdminAPIController {
}
}
@Operation(
summary = " Delete the DiscountRange REST API",
description = "REST API to Deleting the Discount for usertypes"
)
@Operation(summary = " Delete the DiscountRange REST API", description = "REST API to Deleting the Discount for usertypes")
@DeleteMapping("/deleteById/{id}")
public ResponseEntity<String> deleteDiscountRangeById(@PathVariable int id) {
if (discountRangeRepo.existsById(id)) {
@ -523,70 +448,61 @@ public class AdminAPIController {
}
@Operation(
summary = "Retrieving the Discount Details REST API",
description = "REST API to Retrieve the Discount Details for usertypes"
)
//Retrieving the Discount Details
@Operation(summary = "Retrieving the Discount Details REST API", description = "REST API to Retrieve the Discount Details for usertypes")
// Retrieving the Discount Details
@GetMapping("/getDiscountDetails")
public Optional<DiscountRange> getDIscountDetails(@RequestParam("id") int id) {
Optional<DiscountRange> discountdetails = discountRangeRepo.findById(id);
return discountdetails;
}
@Operation(
summary = "Save Reasons REST API",
description = "REST API to save the reasons"
)
//saving the Reason
@Operation(summary = "Save Reasons REST API", description = "REST API to save the reasons")
// saving the Reason
@PostMapping("/saveReason")
public ResponseEntity<?> saveReason(@RequestBody ReasonMaster reasaon) {
return ResponseEntity.ok(reasonMasterService.saveTheReason(reasaon));
}
@Operation(
summary = "All Reasons REST API",
description = "REST API to retrie the allreasons"
)
//retrieving the allreasons
@Operation(summary = "All Reasons REST API", description = "REST API to retrie the allreasons")
// retrieving the allreasons
@GetMapping("/getReasons")
@ResponseBody
public List<ReasonMaster> getAllReasons() {
return reasonMasterService.getAllReasons();
// return reasonMasterService.getAllReasons();
return reasonMasterService.getAllReasonsWithStatus();
}
@Operation(
summary = "Reason Documents by reasonId REST API",
description = "REST API to Get the ReasonDocuments By reasonId"
)
//Getting ReasonDocuments By reasonId
@Operation(summary = "Reason Documents by reasonId REST API", description = "REST API to Get the ReasonDocuments By reasonId")
// Getting ReasonDocuments By reasonId
@GetMapping("/getReasonDocumentDetails")
public List<ReasonDocumentMaster> getReasonDocumentDetails(@RequestParam int reasonId) {
return reasonMasterService.getReasonDocumentDetailsByReasonId(reasonId);
}
@Operation(
summary = "Booking Details by Fromdate,toDate and HallId REST API",
description = "REST API to get the Booking Details by Fromdate,toDate and HallId for GccBlokcing"
)
// @GetMapping("/filter")
// public ResponseEntity<List<BookingResponseDTO>> getFilteredBookings(
// @RequestParam("fromDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate fromDate,
// @RequestParam("toDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate toDate,
// @RequestParam("hallIds") List<Long> hallIds) {
//
// List<BookingDetails> bookings = bookingService.getFilteredBookings(fromDate, toDate, hallIds);
//
// List<BookingResponseDTO> responses = new ArrayList<>();
// for (BookingDetails bookingDetails : bookings) {
// // Fetch GccBlockingDate records for each bookingId
// List<GccBlockingDate> gccBlockedList = blockingDateRepository.getByBookingId(bookingDetails.getBookingId());
// Integer blockingId = gccBlockedList.isEmpty() ? null : gccBlockedList.get(0).getBlockingId();
// responses.add(new BookingResponseDTO(bookingDetails, blockingId));
// }
//
// return ResponseEntity.ok(responses);
// }
@Operation(summary = "Booking Details by Fromdate,toDate and HallId REST API", description = "REST API to get the Booking Details by Fromdate,toDate and HallId for GccBlokcing")
// @GetMapping("/filter")
// public ResponseEntity<List<BookingResponseDTO>> getFilteredBookings(
// @RequestParam("fromDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate
// fromDate,
// @RequestParam("toDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate
// toDate,
// @RequestParam("hallIds") List<Long> hallIds) {
//
// List<BookingDetails> bookings = bookingService.getFilteredBookings(fromDate,
// toDate, hallIds);
//
// List<BookingResponseDTO> responses = new ArrayList<>();
// for (BookingDetails bookingDetails : bookings) {
// // Fetch GccBlockingDate records for each bookingId
// List<GccBlockingDate> gccBlockedList =
// blockingDateRepository.getByBookingId(bookingDetails.getBookingId());
// Integer blockingId = gccBlockedList.isEmpty() ? null :
// gccBlockedList.get(0).getBlockingId();
// responses.add(new BookingResponseDTO(bookingDetails, blockingId));
// }
//
// return ResponseEntity.ok(responses);
// }
@GetMapping("/filter")
public ResponseEntity<Map<String, Object>> getFilteredBookings(
@RequestParam("fromDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate fromDate,
@ -594,7 +510,8 @@ public class AdminAPIController {
@RequestParam("hallIds") List<Long> hallIds) {
List<BookingDetails> bookings = bookingService.getFilteredBookings(fromDate, toDate, hallIds);
List<GccBlockingDate> gccBlockedList = blockingDateRepository.findByFromDateAndToDateBetweenAndHallIdIn(fromDate, toDate, hallIds);
List<GccBlockingDate> gccBlockedList = blockingDateRepository
.findByFromDateAndToDateBetweenAndHallIdIn(fromDate, toDate, hallIds);
Map<String, Object> response = new HashMap<>();
response.put("bookings", bookings);
@ -603,22 +520,19 @@ public class AdminAPIController {
return ResponseEntity.ok(response);
}
@Operation(
summary = " GCC Blocked Booking Details REST API",
description = "REST API to get the GCC Blocked BookingDetails"
)
//retrieving the GCC Blocked BookingDetails
@Operation(summary = " GCC Blocked Booking Details REST API", description = "REST API to get the GCC Blocked BookingDetails")
// retrieving the GCC Blocked BookingDetails
@GetMapping("/blockedevents")
public ResponseEntity<List<GccBlockingDate>> getBlockedEvents(
@RequestParam("fromDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate fromDate,
@RequestParam("toDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate toDate,
@RequestParam("hallIds") List<Long> hallIds
) {
//System.out.println("Blocked Events Request - fromDate: " + fromDate + ", toDate: " + toDate + ", hallIds: " + hallIds );
@RequestParam("hallIds") List<Long> hallIds) {
// System.out.println("Blocked Events Request - fromDate: " + fromDate + ",
// toDate: " + toDate + ", hallIds: " + hallIds );
List<GccBlockingDate> blockedBookings = bookingService.getBlockedEvents(fromDate, toDate, hallIds);
// List<BookingDetails> bookingDetails = bookingService.getByBookingId(fromDate,toDate,hallIds,blockingId,bookingId);
// List<BookingDetails> bookingDetails =
// bookingService.getByBookingId(fromDate,toDate,hallIds,blockingId,bookingId);
if (blockedBookings.isEmpty()) {
// System.out.println("No blocked bookings found.");
@ -632,15 +546,11 @@ public class AdminAPIController {
return ResponseEntity.ok(blockedBookings);
}
@Operation(
summary = "UNBLOCK the gcc Blocked Event REST API",
description = "REST API to unblocking the Gcc blocked Events for blocking"
)
@Operation(summary = "UNBLOCK the gcc Blocked Event REST API", description = "REST API to unblocking the Gcc blocked Events for blocking")
@GetMapping("/cancelByid")
public ResponseEntity<String> cancellationById(@RequestParam int blockingId,
@RequestParam("fromDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate fromDate,
@RequestParam("endDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) {
@RequestParam("fromDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate fromDate,
@RequestParam("endDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) {
// Fetch the blocking date entity
GccBlockingDate blockingDate = blockingDateRepository.findById(blockingId).orElse(null);
@ -668,7 +578,8 @@ public class AdminAPIController {
List<BookingCalendar> bookingCalendars = bookingService.getBookedslots(fromDate, endDate, hallIdList);
if (bookingCalendars.isEmpty()) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("No booking slots found for the given date range and hall IDs.");
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body("No booking slots found for the given date range and hall IDs.");
}
// Iterate over bookingCalendars and update them as needed
@ -712,118 +623,120 @@ public class AdminAPIController {
applicationLogsRepository.save(logs);
return ResponseEntity.ok("Success");
}
// @GetMapping("/cancelByid")
// public ResponseEntity<String> cancellationById(
// @RequestParam int blockingId,
// @RequestParam int bookingId,
// @RequestParam("fromDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate fromDate,
// @RequestParam("endDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate,
// @RequestParam(value = "hallId", required = false) List<Long> hallId) {
//
// System.out.println("Received blockingId: " + blockingId);
// System.out.println("Received bookingId: " + bookingId);
// System.out.println("Received fromDate: " + fromDate);
// System.out.println("Received hallId: " + hallId);
//
// // Retrieve blocking date
// GccBlockingDate blockingDate = blockingDateRepository.findById(blockingId).orElse(null);
//
// if (blockingDate == null) {
// return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Blocking ID not found.");
// }
//
// if (hallId != null && bookingId > 0) {
// // Specific bookingId and hallId selected
//
// // Retrieve and update booking calendar
// List<BookingCalendar> bookingCalendar = bookingService.getBookedslots(fromDate, endDate, hallId);
// if (bookingCalendar.isEmpty()) {
// return ResponseEntity.status(HttpStatus.NOT_FOUND).body("No booking slots found for the given date and hall ID.");
// }
//
// BookingCalendar bookingSlots = bookingCalendar.get(0);
// bookingSlots.setBookingId_1(null);
// bookingSlots.setBookingId_2(null);
// bookingSlots.setMorningSlot(false);
// bookingSlots.setEveningSlot(false);
//
// // Process hallIds and bookingIds
// List<String> hallIdList = Arrays.asList(blockingDate.getHallId().split(","));
// hallIdList.remove(hallId.toString());
// String updatedHallIds = String.join(",", hallIdList);
//
// List<String> bookingIdList = Arrays.asList(blockingDate.getBookingIds().split(","));
// bookingIdList.remove(Integer.toString(bookingId));
// String updatedBookingIds = String.join(",", bookingIdList);
//
// // Update blockingDate with new values
// blockingDate.setHallId(updatedHallIds);
// blockingDate.setBookingIds(updatedBookingIds);
//
// // Create an entry in GccBlockingHistory
// GccBlockingHistory blockingHistory = new GccBlockingHistory();
// blockingHistory.setBlockedStatus(GccBlockingHistory.BlockedStatus.UNBLOCKED);
// blockingHistory.setBlockingReason(blockingHistory.getBlockingReason());
// blockingHistory.setCdate(new Date());
// blockingHistory.setStartDate(blockingHistory.getStartDate());
// blockingHistory.setEndDate(blockingHistory.getEndDate());
// blockingHistory.setUpdatedBy(blockingHistory.getUpdatedBy());
// blockingHistory.setBookingIds(updatedBookingIds);
// blockingHistory.setHallId(updatedHallIds);
// blockingHistoryRepository.save(blockingHistory);
//
// // Update the blocking date status
// blockingDate.setBlockedStatus(GccBlockingDate.BlockedStatus.UNBLOCKED);
// blockingDateRepository.save(blockingDate);
//
// // Save booking calendar updates
// bookingCalendarRepository.save(bookingSlots);
//
// } else {
// // All halls and bookings selected
// // Retrieve and clear all bookings for the date range
// List<BookingCalendar> bookingCalendars = bookingService.getBookedslots(fromDate,endDate,hallId);
// for (BookingCalendar bookingCalendar : bookingCalendars) {
// bookingCalendar.setBookingId_1(null);
// bookingCalendar.setBookingId_2(null);
// bookingCalendar.setMorningSlot(false);
// bookingCalendar.setEveningSlot(false);
// bookingCalendarRepository.save(bookingCalendar);
// }
//
// // Update blocking date status to UNBLOCKED
// blockingDate.setBlockedStatus(GccBlockingDate.BlockedStatus.UNBLOCKED);
// blockingDateRepository.save(blockingDate);
//
// // Create an entry in GccBlockingHistory
// GccBlockingHistory blockingHistory = new GccBlockingHistory();
// blockingHistory.setBlockedStatus(GccBlockingHistory.BlockedStatus.UNBLOCKED);
// blockingHistory.setBlockingReason(blockingHistory.getBlockingReason());
// blockingHistory.setCdate(new Date());
// blockingHistory.setStartDate(blockingHistory.getStartDate());
// blockingHistory.setEndDate(blockingHistory.getEndDate());
// blockingHistory.setUpdatedBy(blockingHistory.getUpdatedBy());
// blockingHistoryRepository.save(blockingHistory);
// }
//
// return ResponseEntity.ok("Success");
// }
@Operation(
summary = "HAll IMAGES by HallId REST API",
description = "REST API to get the hall Images by Hall Id"
)
//retrieving Hall Images by Hallid
// @GetMapping("/cancelByid")
// public ResponseEntity<String> cancellationById(
// @RequestParam int blockingId,
// @RequestParam int bookingId,
// @RequestParam("fromDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate
// fromDate,
// @RequestParam("endDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate
// endDate,
// @RequestParam(value = "hallId", required = false) List<Long> hallId) {
//
// System.out.println("Received blockingId: " + blockingId);
// System.out.println("Received bookingId: " + bookingId);
// System.out.println("Received fromDate: " + fromDate);
// System.out.println("Received hallId: " + hallId);
//
// // Retrieve blocking date
// GccBlockingDate blockingDate =
// blockingDateRepository.findById(blockingId).orElse(null);
//
// if (blockingDate == null) {
// return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Blocking ID not
// found.");
// }
//
// if (hallId != null && bookingId > 0) {
// // Specific bookingId and hallId selected
//
// // Retrieve and update booking calendar
// List<BookingCalendar> bookingCalendar =
// bookingService.getBookedslots(fromDate, endDate, hallId);
// if (bookingCalendar.isEmpty()) {
// return ResponseEntity.status(HttpStatus.NOT_FOUND).body("No booking slots
// found for the given date and hall ID.");
// }
//
// BookingCalendar bookingSlots = bookingCalendar.get(0);
// bookingSlots.setBookingId_1(null);
// bookingSlots.setBookingId_2(null);
// bookingSlots.setMorningSlot(false);
// bookingSlots.setEveningSlot(false);
//
// // Process hallIds and bookingIds
// List<String> hallIdList = Arrays.asList(blockingDate.getHallId().split(","));
// hallIdList.remove(hallId.toString());
// String updatedHallIds = String.join(",", hallIdList);
//
// List<String> bookingIdList =
// Arrays.asList(blockingDate.getBookingIds().split(","));
// bookingIdList.remove(Integer.toString(bookingId));
// String updatedBookingIds = String.join(",", bookingIdList);
//
// // Update blockingDate with new values
// blockingDate.setHallId(updatedHallIds);
// blockingDate.setBookingIds(updatedBookingIds);
//
// // Create an entry in GccBlockingHistory
// GccBlockingHistory blockingHistory = new GccBlockingHistory();
// blockingHistory.setBlockedStatus(GccBlockingHistory.BlockedStatus.UNBLOCKED);
// blockingHistory.setBlockingReason(blockingHistory.getBlockingReason());
// blockingHistory.setCdate(new Date());
// blockingHistory.setStartDate(blockingHistory.getStartDate());
// blockingHistory.setEndDate(blockingHistory.getEndDate());
// blockingHistory.setUpdatedBy(blockingHistory.getUpdatedBy());
// blockingHistory.setBookingIds(updatedBookingIds);
// blockingHistory.setHallId(updatedHallIds);
// blockingHistoryRepository.save(blockingHistory);
//
// // Update the blocking date status
// blockingDate.setBlockedStatus(GccBlockingDate.BlockedStatus.UNBLOCKED);
// blockingDateRepository.save(blockingDate);
//
// // Save booking calendar updates
// bookingCalendarRepository.save(bookingSlots);
//
// } else {
// // All halls and bookings selected
// // Retrieve and clear all bookings for the date range
// List<BookingCalendar> bookingCalendars =
// bookingService.getBookedslots(fromDate,endDate,hallId);
// for (BookingCalendar bookingCalendar : bookingCalendars) {
// bookingCalendar.setBookingId_1(null);
// bookingCalendar.setBookingId_2(null);
// bookingCalendar.setMorningSlot(false);
// bookingCalendar.setEveningSlot(false);
// bookingCalendarRepository.save(bookingCalendar);
// }
//
// // Update blocking date status to UNBLOCKED
// blockingDate.setBlockedStatus(GccBlockingDate.BlockedStatus.UNBLOCKED);
// blockingDateRepository.save(blockingDate);
//
// // Create an entry in GccBlockingHistory
// GccBlockingHistory blockingHistory = new GccBlockingHistory();
// blockingHistory.setBlockedStatus(GccBlockingHistory.BlockedStatus.UNBLOCKED);
// blockingHistory.setBlockingReason(blockingHistory.getBlockingReason());
// blockingHistory.setCdate(new Date());
// blockingHistory.setStartDate(blockingHistory.getStartDate());
// blockingHistory.setEndDate(blockingHistory.getEndDate());
// blockingHistory.setUpdatedBy(blockingHistory.getUpdatedBy());
// blockingHistoryRepository.save(blockingHistory);
// }
//
// return ResponseEntity.ok("Success");
// }
@Operation(summary = "HAll IMAGES by HallId REST API", description = "REST API to get the hall Images by Hall Id")
// retrieving Hall Images by Hallid
@GetMapping("/getImageById")
public List<HallImages> getImageDetails(@RequestParam int hallId) {
return hallService.getHallImages(hallId);
}
@Operation(
summary = "GCC Blocking REST API",
description = "REST API to Block the Halls by Admin"
)
//GccBlocking Api
@Operation(summary = "GCC Blocking REST API", description = "REST API to Block the Halls by Admin")
// GccBlocking Api
@PostMapping("/cancelAll")
public ResponseEntity<String> cancelAllBookings(
@RequestParam("fromDate") String fromDate,
@ -844,7 +757,8 @@ public class AdminAPIController {
.collect(Collectors.toList());
// Call the service with descriptions and documents
bookingService.cancelAllBookings(fromDate, toDate, hallIdsList, reasonforblocking, selectedBookings, updatedBy, descriptions, documents);
bookingService.cancelAllBookings(fromDate, toDate, hallIdsList, reasonforblocking, selectedBookings, updatedBy,
descriptions, documents);
String adminname = (String) session.getAttribute("usertype");
Integer loginid = (Integer) session.getAttribute("id");
ApplicationLogs logs = new ApplicationLogs();
@ -864,35 +778,39 @@ public class AdminAPIController {
return ResponseEntity.ok("Success");
}
// @PostMapping("/blockhall")
// public ResponseEntity<String> blockHall(
// @RequestParam("blockingId") Integer blockingId,
// @RequestParam("hallID") String hallID, // Ensure this matches the parameter name used in AJAX
// @RequestParam(value = "selectedBookings", required = false) List<String> selectedBookings,
// HttpSession session) {
//
// String updatedBy = (String) session.getAttribute("employeeId");
// Optional<GccBlockingDate> gccblocking = blockingDateRepository.findById(blockingId);
// GccBlockingDate gccblockingdata = gccblocking.get();
//
// // Convert startDate and endDate to String
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
// String startDateString = sdf.format(gccblockingdata.getStartDate());
// String endDateString = sdf.format(gccblockingdata.getEndDate());
//
// // Split and convert hall IDs
// List<Long> hallIdsList = Arrays.stream(hallID.split(","))
// .map(Long::parseLong)
// .collect(Collectors.toList());
//
// System.out.println("selected BookingIds: " + selectedBookings);
//
// // Pass the formatted date strings
// bookingService.cancelAllBookings(startDateString, endDateString, hallIdsList, gccblockingdata.getDepartment(), gccblockingdata.getBlockingReason(), selectedBookings, updatedBy);
//
// return ResponseEntity.ok("Success");
// }
// @PostMapping("/blockhall")
// public ResponseEntity<String> blockHall(
// @RequestParam("blockingId") Integer blockingId,
// @RequestParam("hallID") String hallID, // Ensure this matches the parameter
// name used in AJAX
// @RequestParam(value = "selectedBookings", required = false) List<String>
// selectedBookings,
// HttpSession session) {
//
// String updatedBy = (String) session.getAttribute("employeeId");
// Optional<GccBlockingDate> gccblocking =
// blockingDateRepository.findById(blockingId);
// GccBlockingDate gccblockingdata = gccblocking.get();
//
// // Convert startDate and endDate to String
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
// String startDateString = sdf.format(gccblockingdata.getStartDate());
// String endDateString = sdf.format(gccblockingdata.getEndDate());
//
// // Split and convert hall IDs
// List<Long> hallIdsList = Arrays.stream(hallID.split(","))
// .map(Long::parseLong)
// .collect(Collectors.toList());
//
// System.out.println("selected BookingIds: " + selectedBookings);
//
// // Pass the formatted date strings
// bookingService.cancelAllBookings(startDateString, endDateString, hallIdsList,
// gccblockingdata.getDepartment(), gccblockingdata.getBlockingReason(),
// selectedBookings, updatedBy);
//
// return ResponseEntity.ok("Success");
// }
@GetMapping("/bookingdetailsByuserId")
public List<BookingDetails> getuserDetails(@RequestParam Integer userId) {
@ -901,55 +819,64 @@ public class AdminAPIController {
@GetMapping("/settlement-approved")
public ResponseEntity<List<Settlement>> getApprovedSettlements(HttpSession session) {
List<Settlement> approvedSettlements = settlementRepository.findByBookingDetailsRefundStatus(RefundStatus.APPROVED);
List<Settlement> approvedSettlements = settlementRepository
.findByBookingDetailsRefundStatus(RefundStatus.APPROVED);
return ResponseEntity.ok(approvedSettlements);
}
// @PostMapping("/complete-refund")
// public ResponseEntity<String> completeRefund(@RequestBody List<String> bookingIds, HttpSession session, HttpServletResponse response) throws IOException {
// String token = (String) session.getAttribute("jwtToken");
// //System.out.println("tokensssssssss" + token);
//
// // Validate JWT token
// if (token != null && jwtUtil.validateToken(token)) {
// // System.out.println("tokennnnnnnnnnnnnnns" + token);
// try {
// // System.out.println("Received booking IDs for refund: " + bookingIds);
//
// List<String> bookids = bookingService.processRefundRequests(bookingIds);
//
// if (!bookids.isEmpty()) {
// // Prepare and return error response if there are errors
// StringBuilder errorResponse = new StringBuilder("Errors processing refund for IDs: ");
// for (String bookId : bookids) {
// errorResponse.append(bookId).append(", ");
// }
// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse.toString());
// }
//
// return ResponseEntity.ok("Refund completed successfully");
// } catch (Exception e) {
// e.printStackTrace();
// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error processing refund: " + e.getMessage());
// }
// } else {
// // Token is invalid or not present, redirect to login
// session.invalidate(); // Invalidate the session to clear all session attributes
// response.sendRedirect("/login"); // Redirect to the login page
// return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); // Return HTTP 401 Unauthorized
// }
// }
// @GetMapping("/Gccblocking")
// public ResponseEntity<List<Object>> getGccBlockingEvents(@RequestParam("hallId") int hallId) {
// System.out.println("Received hallId: " + hallId);
//
// List<Object> results = bookingService.getGccBlockingEvents(hallId);
//
// return ResponseEntity.ok(results);
// }
// @PostMapping("/complete-refund")
// public ResponseEntity<String> completeRefund(@RequestBody List<String>
// bookingIds, HttpSession session, HttpServletResponse response) throws
// IOException {
// String token = (String) session.getAttribute("jwtToken");
// //System.out.println("tokensssssssss" + token);
//
// // Validate JWT token
// if (token != null && jwtUtil.validateToken(token)) {
// // System.out.println("tokennnnnnnnnnnnnnns" + token);
// try {
// // System.out.println("Received booking IDs for refund: " + bookingIds);
//
// List<String> bookids = bookingService.processRefundRequests(bookingIds);
//
// if (!bookids.isEmpty()) {
// // Prepare and return error response if there are errors
// StringBuilder errorResponse = new StringBuilder("Errors processing refund for
// IDs: ");
// for (String bookId : bookids) {
// errorResponse.append(bookId).append(", ");
// }
// return
// ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse.toString());
// }
//
// return ResponseEntity.ok("Refund completed successfully");
// } catch (Exception e) {
// e.printStackTrace();
// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error
// processing refund: " + e.getMessage());
// }
// } else {
// // Token is invalid or not present, redirect to login
// session.invalidate(); // Invalidate the session to clear all session
// attributes
// response.sendRedirect("/login"); // Redirect to the login page
// return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); // Return HTTP
// 401 Unauthorized
// }
// }
// @GetMapping("/Gccblocking")
// public ResponseEntity<List<Object>>
// getGccBlockingEvents(@RequestParam("hallId") int hallId) {
// System.out.println("Received hallId: " + hallId);
//
// List<Object> results = bookingService.getGccBlockingEvents(hallId);
//
// return ResponseEntity.ok(results);
// }
@GetMapping("/Gccblocking")
public ResponseEntity<List<Object>> getGccBlockingEvents(@RequestParam("hallId") String hallId) {
//System.out.println("Received hallId: " + hallId);
// System.out.println("Received hallId: " + hallId);
List<Object> results = bookingService.getGccBlockingEvents(hallId);
@ -962,7 +889,7 @@ public class AdminAPIController {
@RequestParam int blockingId) {
// System.out.println("Received hallIds: " + hallIds);
//System.out.println("Received blockingId: " + blockingId);
// System.out.println("Received blockingId: " + blockingId);
List<Integer> hallIdList;
try {
@ -987,13 +914,15 @@ public class AdminAPIController {
for (int hallId : hallIdList) {
int bookingCount = bookingDetailsRepository.countByHallIdAndBookingDateBetween(hallId, startDate, endDate);
//System.out.println("bookingCount==="+bookingCount);
// System.out.println("bookingCount==="+bookingCount);
Optional<HallDetails> hallDetailsOpt = hallDetailsRepository.findById(hallId);
if (hallDetailsOpt.isPresent()) {
HallDetails hallDetails = hallDetailsOpt.get();
List<Integer> bookingIds = bookingDetailsRepository.findBookingIdsByHallIdAndBookingDateBetween(hallId, startDate, endDate);
// System.out.println("Booking IDs for hallId " + hallId + ": " + bookingIds); // Add this line
List<Integer> bookingIds = bookingDetailsRepository.findBookingIdsByHallIdAndBookingDateBetween(hallId,
startDate, endDate);
// System.out.println("Booking IDs for hallId " + hallId + ": " + bookingIds);
// // Add this line
Map<String, Object> hallInfo = new HashMap<>();
hallInfo.put("hallName", hallDetails.getHallName());
@ -1012,10 +941,10 @@ public class AdminAPIController {
@GetMapping("/getbookingdetails")
public ResponseEntity<List<BookingDetails>> getBookingDetails(@RequestParam("bookingId") Long bookingId) {
//System.out.println("Received bookingId: " + bookingId);
// System.out.println("Received bookingId: " + bookingId);
try {
List<BookingDetails> details = bookingService.findBookingDetailsByBookingId(bookingId);
//System.out.println("bookingdetails==="+details);
// System.out.println("bookingdetails==="+details);
return ResponseEntity.ok(details);
} catch (Exception e) {
e.printStackTrace();
@ -1023,7 +952,6 @@ public class AdminAPIController {
}
}
@GetMapping("/blockedHallsByHallIdAndReason")
@ResponseBody
public Map<String, Object> viewBlockedHallsByHallIdAndReason(
@ -1032,11 +960,13 @@ public class AdminAPIController {
@RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date startDate,
@RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date endDate) {
List<GccBlockingDate> blockedHalls = blockingDateRepository.findByBlockingReasonAndDateRange(blockingReason, startDate, endDate);
List<GccBlockingDate> blockedHalls = blockingDateRepository.findByBlockingReasonAndDateRange(blockingReason,
startDate, endDate);
// Ensure distinct by hallId and other keys
List<GccBlockingDate> uniqueGccBlockingDates = blockedHalls.stream()
.filter(distinctByKey(g -> Arrays.asList(g.getHallId(), g.getBlockingReason(), g.getStartDate(), g.getEndDate())))
.filter(distinctByKey(
g -> Arrays.asList(g.getHallId(), g.getBlockingReason(), g.getStartDate(), g.getEndDate())))
.collect(Collectors.toList());
// Prepare response data
@ -1083,7 +1013,6 @@ public class AdminAPIController {
return response;
}
// Utility method to ensure distinct by a key
private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Set<Object> seen = new HashSet<>();
@ -1092,7 +1021,8 @@ public class AdminAPIController {
// Method to calculate number of bookings
private int calculateBookings(HallDetails hall, GccBlockingDate blockedHall) {
return blockingDateRepository.countBlockedBookings(hall.getHallId(), blockedHall.getStartDate(), blockedHall.getEndDate());
return blockingDateRepository.countBlockedBookings(hall.getHallId(), blockedHall.getStartDate(),
blockedHall.getEndDate());
}
private double calculateRefund(HallDetails hall, GccBlockingDate blockedHall) {
@ -1100,7 +1030,7 @@ public class AdminAPIController {
return 0.0;
}
//admin dashboard
// admin dashboard
@GetMapping("/bookingstatistics")
public ResponseEntity<Map<String, Map<String, Integer>>> getBookingStatistics(
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate fromDate,
@ -1111,7 +1041,8 @@ public class AdminAPIController {
@RequestParam(required = false, defaultValue = "ALL") String userType) {
try {
Map<String, Map<String, Integer>> statistics = bookingService.getBookingStatistics(fromDate, toDate, zone, division, hallid, userType);
Map<String, Map<String, Integer>> statistics = bookingService.getBookingStatistics(fromDate, toDate, zone,
division, hallid, userType);
return ResponseEntity.ok(statistics);
} catch (Exception e) {
// Log the exception and return an appropriate error response
@ -1135,18 +1066,18 @@ public class AdminAPIController {
@PostMapping("/savenewHallImages")
public ResponseEntity<?> updateHallImages(@RequestParam("hallId") Integer hallId,
@RequestParam("newHallImages") MultipartFile[] newHallImages) {
@RequestParam("newHallImages") MultipartFile[] newHallImages) {
// Call the service method to update the hall images
hallService.updatenewHallImages(hallId, newHallImages);
return ResponseEntity.ok().build();
}
// @DeleteMapping("/deleteHallImage/{hallImageId}")
// public ResponseEntity<?> deleteHallImage(@PathVariable Long hallImageId) {
// // Call the service method to delete the hall image
// hallService.deleteHallImage(hallImageId);
// return ResponseEntity.ok().build();
// }
// @DeleteMapping("/deleteHallImage/{hallImageId}")
// public ResponseEntity<?> deleteHallImage(@PathVariable Long hallImageId) {
// // Call the service method to delete the hall image
// hallService.deleteHallImage(hallImageId);
// return ResponseEntity.ok().build();
// }
@PutMapping("/updateHallImage/{hallImageId}")
public ResponseEntity<Map<String, String>> updateHallImage(
@ -1161,7 +1092,8 @@ public class AdminAPIController {
} catch (IllegalArgumentException e) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Collections.singletonMap("error", e.getMessage()));
} catch (IOException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Collections.singletonMap("error", "Failed to update image"));
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Collections.singletonMap("error", "Failed to update image"));
}
}
@ -1223,7 +1155,7 @@ public class AdminAPIController {
}
}
//gccapps
// gccapps
@GetMapping("/viewsettlement-pending")
public ResponseEntity<Map<String, Object>> viewSettlementPendingMaster(HttpSession session) {
@ -1239,7 +1171,6 @@ public class AdminAPIController {
return ResponseEntity.ok(response);
}
@GetMapping("/viewsettlement-complete")
public ResponseEntity<Map<String, Object>> viewSettlementcompleteMaster(HttpSession session) {
@ -1342,10 +1273,16 @@ public class AdminAPIController {
List<Users> userList = handleUserRequest(request, fromDate, toDate, userstatus, usertype);
List<Object[]> bookingList = handleBookingRequest(request, fromDate, toDate, bookingStatus, bookingId);
List<BookingDetails> bookingSettlementList = handleBookingSettlementRequest(request, fromDate, toDate, refundStatus);
List<Object[]> paymentList = request.equals("3") ? bookingService.getAllPaymentsDetails(fromDate, toDate) : new ArrayList<>();
List<Object[]> userbookingList = request.equals("4") ? bookingService.getBookingUserDetailsReport(fromDate, toDate) : new ArrayList<>();
List<Object[]> hallbookingList = request.equals("5") ? bookingService.getBookingHallDetailsReport(fromDate, toDate) : new ArrayList<>();
List<BookingDetails> bookingSettlementList = handleBookingSettlementRequest(request, fromDate, toDate,
refundStatus);
List<Object[]> paymentList = request.equals("3") ? bookingService.getAllPaymentsDetails(fromDate, toDate)
: new ArrayList<>();
List<Object[]> userbookingList = request.equals("4")
? bookingService.getBookingUserDetailsReport(fromDate, toDate)
: new ArrayList<>();
List<Object[]> hallbookingList = request.equals("5")
? bookingService.getBookingHallDetailsReport(fromDate, toDate)
: new ArrayList<>();
response.put("users", userList);
response.put("bookings", bookingList);
@ -1365,7 +1302,8 @@ public class AdminAPIController {
return new ResponseEntity<>(response, HttpStatus.OK);
}
private List<Users> handleUserRequest(String request, String fromDate, String toDate, String userstatus, String usertype) {
private List<Users> handleUserRequest(String request, String fromDate, String toDate, String userstatus,
String usertype) {
if (!request.equals("1")) {
return new ArrayList<>();
}
@ -1381,7 +1319,8 @@ public class AdminAPIController {
return userService.getAllUsers(fromDate, toDate);
}
private List<Object[]> handleBookingRequest(String request, String fromDate, String toDate, String bookingStatus, Long bookingId) {
private List<Object[]> handleBookingRequest(String request, String fromDate, String toDate, String bookingStatus,
Long bookingId) {
if (!request.equals("2")) {
return new ArrayList<>();
}
@ -1394,7 +1333,8 @@ public class AdminAPIController {
}
}
private List<BookingDetails> handleBookingSettlementRequest(String request, String fromDate, String toDate, String refundStatus) {
private List<BookingDetails> handleBookingSettlementRequest(String request, String fromDate, String toDate,
String refundStatus) {
if (!request.equals("6")) {
return new ArrayList<>();
}
@ -1410,7 +1350,6 @@ public class AdminAPIController {
return ResponseEntity.ok(halldetails);
}
@GetMapping("/listgccblocking")
public ResponseEntity<Map<String, Object>> getGccBlocking() {
@ -1495,7 +1434,7 @@ public class AdminAPIController {
@PostMapping("/uploadnoc")
public ResponseEntity<String> uploadnoc(@RequestParam("nocFile") MultipartFile file,
@RequestParam("bookingid") int bookingId) {
@RequestParam("bookingid") int bookingId) {
try {
System.out.println("Received file: " + file.getOriginalFilename());
System.out.println("Booking ID: " + bookingId);
@ -1504,7 +1443,8 @@ public class AdminAPIController {
return ResponseEntity.ok("File uploaded and saved successfully");
} catch (Exception e) {
System.err.println("Error during file upload: " + e.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("File upload failed: " + e.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("File upload failed: " + e.getMessage());
}
}
}

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

@ -65,17 +65,13 @@ import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.AllArgsConstructor;
@Tag(
name = "CRUD REST APIs for Officer in CommunityHall",
description = "CRUD REST APIs in CommunityHall to CREATE, UPDATE, FETCH AND DELETE Booking details"
)
@Tag(name = "CRUD REST APIs for Officer in CommunityHall", description = "CRUD REST APIs in CommunityHall to CREATE, UPDATE, FETCH AND DELETE Booking details")
@RestController
@RequestMapping("/victoriahallbooking/api/officer")
@AllArgsConstructor
@Validated
public class OfficerAPIController {
//ak// ak
// ak// ak
@Autowired
private SettlementHistoryRepository settlementHistoryRepository;
@ -128,87 +124,74 @@ public class OfficerAPIController {
@Autowired
private ApplicationLogsRepository applicationLogsRepository;
@Operation(
summary = "Retriving the User Details by userId REST API",
description = "REST API for Retriving the User Details by UserId"
)
//Getting User Details by User Id
@Operation(summary = "Retriving the User Details by userId REST API", description = "REST API for Retriving the User Details by UserId")
// Getting User Details by User Id
@GetMapping("/getUserDetails")
public ResponseEntity<?> getUsersByID(HttpServletRequest request, @RequestParam String usersid){
Users user =userServiceImpl.getUserById(Integer.parseInt(usersid));
return ResponseEntity.ok(user);
}
@Operation(
summary = "Settlement List where the Refund Status is WAITING REST API",
description = "REST API for Retriving the Settlement List where the Refund Status is WAITING"
)
//retrieving the Settlement List by Refund Status is WAITING
@GetMapping("/waiting-refund")
public List<Settlement> getSettlementsWithWaitingRefund() {
return settlementService.getSettlementListWithWaitingRefund();
}
@Operation(
summary = "Settlement List by Settlement Id REST API",
description = "REST API for Retriving the Settlement List by Settlement Id"
)
//retrieving the Settlement List by Settlement Id
public ResponseEntity<?> getUsersByID(HttpServletRequest request, @RequestParam String usersid) {
Users user = userServiceImpl.getUserById(Integer.parseInt(usersid));
return ResponseEntity.ok(user);
}
@Operation(summary = "Settlement List where the Refund Status is WAITING REST API", description = "REST API for Retriving the Settlement List where the Refund Status is WAITING")
// retrieving the Settlement List by Refund Status is WAITING
@GetMapping("/waiting-refund")
public List<Settlement> getSettlementsWithWaitingRefund() {
return settlementService.getSettlementListWithWaitingRefund();
}
@Operation(summary = "Settlement List by Settlement Id REST API", description = "REST API for Retriving the Settlement List by Settlement Id")
// retrieving the Settlement List by Settlement Id
@GetMapping("/getSettlementList")
public ResponseEntity<BookingDetails> getBookingDetailsWithSettlement(HttpServletRequest request, @RequestParam String settlementsid) {
BookingDetails bookingDetails = bookingServiceImpl.getBookingDetailsWithSettlement(Integer.parseInt(settlementsid));
public ResponseEntity<BookingDetails> getBookingDetailsWithSettlement(HttpServletRequest request,
@RequestParam String settlementsid) {
BookingDetails bookingDetails = bookingServiceImpl
.getBookingDetailsWithSettlement(Integer.parseInt(settlementsid));
System.out.println("bookingDetails:12 " + bookingDetails);
return ResponseEntity.ok(bookingDetails);
return ResponseEntity.ok(bookingDetails);
}
@GetMapping("/getsettlementListbyid")
public ResponseEntity<Optional<Settlement>> getsettlementlist(HttpServletRequest request, @RequestParam int settlementsid) {
Optional<Settlement> settlementlist=settlementRepository.findById(settlementsid);
return ResponseEntity.ok(settlementlist);
public ResponseEntity<Optional<Settlement>> getsettlementlist(HttpServletRequest request,
@RequestParam int settlementsid) {
Optional<Settlement> settlementlist = settlementRepository.findById(settlementsid);
return ResponseEntity.ok(settlementlist);
}
@Operation(
summary = "Booking Details by Booking Id REST API",
description = "REST API for Retriving the Booking Details by Booking Id"
)
//retrieving the Booking Details by Booking Id
@Operation(summary = "Booking Details by Booking Id REST API", description = "REST API for Retriving the Booking Details by Booking Id")
// retrieving the Booking Details by Booking Id
@GetMapping("/getBookingDetails")
public ResponseEntity<?> getBookingsById(HttpServletRequest request, @RequestParam String bookingsId){
BookingDetails book =bookingServiceImpl.getBookingsById(Integer.parseInt(bookingsId));
return ResponseEntity.ok(book);
}
@Operation(
summary = "Settlement APPROVED REST API",
description = "REST API for Updating the Refund Status to Approved by Settlement Id If the settlement is Approved"
)
//Updating the Refund Status to Approved by Settlement Id If the settlement is Approved
public ResponseEntity<?> getBookingsById(HttpServletRequest request, @RequestParam String bookingsId) {
BookingDetails book = bookingServiceImpl.getBookingsById(Integer.parseInt(bookingsId));
return ResponseEntity.ok(book);
}
@Operation(summary = "Settlement APPROVED REST API", description = "REST API for Updating the Refund Status to Approved by Settlement Id If the settlement is Approved")
// Updating the Refund Status to Approved by Settlement Id If the settlement is
// Approved
@PostMapping("/updateApprovedSettlementStatus/{settlementId}") // need to check this API for settlement approval
public ResponseEntity<Object> updateApprovedSettlementStatus(
@PathVariable("settlementId") int settlementId,
@RequestParam("status") BookingDetails.RefundStatus status,
@RequestParam("comments") String comments) {
Map<String, Object> response = new HashMap<>();
Map<String, Object> response = new HashMap<>();
try {
System.out.println("settlementId1: " + settlementId);
System.out.println("status"+status);
System.out.println("comments"+comments);
System.out.println("status" + status);
System.out.println("comments" + comments);
// Update settlement status
Settlement updateSettlement = settlementService.updateSettlementStatus(settlementId, status, comments);
if (updateSettlement == null) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
System.out.println("updateSettlement12"+updateSettlement);
//ak
// Set approvedFlag and approvedFlagDate
updateSettlement.setApprovedFlag(1);
updateSettlement.setApprovedFlagDate(new Date());
settlementRepository.save(updateSettlement);
//ak
System.out.println("updateSettlement12" + updateSettlement);
// ak
// Set approvedFlag and approvedFlagDate
updateSettlement.setApprovedFlag(1);
updateSettlement.setApprovedFlagDate(new Date());
settlementRepository.save(updateSettlement);
// ak
// Log the action
String adminname = (String) session.getAttribute("usertype");
@ -231,458 +214,439 @@ public class OfficerAPIController {
applicationLogsRepository.save(logs);
// Process refund request
String refundResponse = bookingServiceImpl.processRefundRequest(updateSettlement.getBookingDetails().getBookingId());
//ak
// Prepare response map
String refundResponse = bookingServiceImpl
.processRefundRequest(updateSettlement.getBookingDetails().getBookingId());
// ak
// Prepare response map
response.put("settlement", updateSettlement);
response.put("approvedFlag", updateSettlement.getApprovedFlag());
response.put("approvedFlagDate", updateSettlement.getApprovedFlagDate());
response.put("settlement", updateSettlement);
response.put("approvedFlag", updateSettlement.getApprovedFlag());
response.put("approvedFlagDate", updateSettlement.getApprovedFlagDate());
if (refundResponse.contains("successful")) {
// Refund success, return updated settlement and status
//return new ResponseEntity<>(updateSettlement, HttpStatus.OK);
// return new ResponseEntity<>(updateSettlement, HttpStatus.OK);
return new ResponseEntity<>(response, HttpStatus.OK);
} else {
// Refund failure, update refund status to FAILURE
bookingService.updateRefundStatus(updateSettlement.getBookingDetails().getBookingId(), BookingDetails.RefundStatus.FAILURE);
Map<String, Object> responses = new HashMap<>();
responses.put("approvedFlag", 1);
responses.put("message", "Refund processing failed: " + refundResponse);
responses.put("status", "FAILURE");
return new ResponseEntity<>(responses, HttpStatus.INTERNAL_SERVER_ERROR);
//return new ResponseEntity<>("Refund processing failed: " + refundResponse, HttpStatus.INTERNAL_SERVER_ERROR);
bookingService.updateRefundStatus(updateSettlement.getBookingDetails().getBookingId(),
BookingDetails.RefundStatus.FAILURE);
Map<String, Object> responses = new HashMap<>();
responses.put("approvedFlag", 1);
responses.put("message", "Refund processing failed: " + refundResponse);
responses.put("status", "FAILURE");
return new ResponseEntity<>(responses, HttpStatus.INTERNAL_SERVER_ERROR);
// return new ResponseEntity<>("Refund processing failed: " + refundResponse,
// HttpStatus.INTERNAL_SERVER_ERROR);
}
} catch (Exception e) {
response.put("approvedFlag", 1);
response.put("message", "Exception while approving settlement: " + e.getMessage());
return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
response.put("approvedFlag", 1);
response.put("message", "Exception while approving settlement: " + e.getMessage());
return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
//return new ResponseEntity<>("An error occurred while processing the settlement for Settlement ID: " + settlementId, HttpStatus.INTERNAL_SERVER_ERROR);
// return new ResponseEntity<>("An error occurred while processing the
// settlement for Settlement ID: " + settlementId,
// HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@Operation(
summary = "Settlement APPROVED REST API",
description = "REST API for Updating the Refund Status to Approved by Settlement Id If the settlement is Approved"
)
//Updating the Refund Status to Rejected by Settlement Id If the settlement is Rejected
@Operation(summary = "Settlement APPROVED REST API", description = "REST API for Updating the Refund Status to Approved by Settlement Id If the settlement is Approved")
// Updating the Refund Status to Rejected by Settlement Id If the settlement is
// Rejected
@PostMapping("/updateRejectSettlementStatus/{settlementId}")
public ResponseEntity<Settlement> updateRejectSettlementStatus(
@PathVariable("settlementId") int settlementId,
@RequestParam("status") BookingDetails.RefundStatus status,
@RequestParam("comments") String comments){
Settlement updateSettlement = settlementService.updateRejectSettlementStatus(settlementId, status, comments);
String adminname = (String) session.getAttribute("usertype");
Integer loginid = (Integer) session.getAttribute("id");
ApplicationLogs logs=new ApplicationLogs();
logs.setComments("Action by " + adminname);
logs.setLoginId(loginid);
logs.setBookingId(updateSettlement.getBookingDetails().getBookingId());
logs.setLogType("Booking Status:-"+status.toString());
InetAddress inetAddress;
try {
inetAddress = InetAddress.getLocalHost();
String hostname = InetAddress.getLocalHost().getHostName();
logs.setIpaddress(inetAddress.getHostAddress());
logs.setSystemName(hostname);
} catch (UnknownHostException e) {
e.printStackTrace();
}
applicationLogsRepository.save(logs);
if (updateSettlement != null) {
return new ResponseEntity<>(updateSettlement, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
@RequestParam("comments") String comments) {
Settlement updateSettlement = settlementService.updateRejectSettlementStatus(settlementId, status, comments);
String adminname = (String) session.getAttribute("usertype");
Integer loginid = (Integer) session.getAttribute("id");
ApplicationLogs logs = new ApplicationLogs();
logs.setComments("Action by " + adminname);
logs.setLoginId(loginid);
logs.setBookingId(updateSettlement.getBookingDetails().getBookingId());
logs.setLogType("Booking Status:-" + status.toString());
InetAddress inetAddress;
try {
inetAddress = InetAddress.getLocalHost();
String hostname = InetAddress.getLocalHost().getHostName();
logs.setIpaddress(inetAddress.getHostAddress());
logs.setSystemName(hostname);
} catch (UnknownHostException e) {
e.printStackTrace();
}
applicationLogsRepository.save(logs);
if (updateSettlement != null) {
return new ResponseEntity<>(updateSettlement, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@Operation(
summary = "USER STATUS APPROVED REST API",
description = "REST API for Updating the user Status Approved"
)
//Updating the user Status Approved
@Operation(summary = "USER STATUS APPROVED REST API", description = "REST API for Updating the user Status Approved")
// Updating the user Status Approved
@PostMapping("/updateApprovedStatus/{userId}")
public ResponseEntity<Users> updateApprovedStatus(
@PathVariable("userId") int userId,
@RequestParam("status") Users.userStatus status,
@RequestParam("comments") String comments) {
Users updatedUser = userService.updateUserStatus(userId, status, comments);
if (updatedUser != null) {
return new ResponseEntity<>(updatedUser, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
@PathVariable("userId") int userId,
@RequestParam("status") Users.userStatus status,
@RequestParam("comments") String comments) {
Users updatedUser = userService.updateUserStatus(userId, status, comments);
if (updatedUser != null) {
return new ResponseEntity<>(updatedUser, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@Operation(
summary = "USER STATUS REJECTED REST API",
description = "REST API for Updating the user Status Rejected"
)
//Updating the user Status Rejected
@Operation(summary = "USER STATUS REJECTED REST API", description = "REST API for Updating the user Status Rejected")
// Updating the user Status Rejected
@PostMapping("/updateRejectStatus/{userId}")
public ResponseEntity<Users> updateRejectStatus(
@PathVariable("userId") int userId,
@RequestParam("status") Users.userStatus status,
@RequestParam("comments") String comments) {
@PathVariable("userId") int userId,
@RequestParam("status") Users.userStatus status,
@RequestParam("comments") String comments) {
Users updatedUser = userService.updateUserStatus(userId, status, comments);
Users updatedUser = userService.updateUserStatus(userId, status, comments);
if (updatedUser != null) {
return new ResponseEntity<>(updatedUser, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
if (updatedUser != null) {
return new ResponseEntity<>(updatedUser, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@Operation(
summary = "BOOKING STATUS APPROVED REST API",
description = "REST API for Updating the Booking Status Approved by Booking Id"
)
//Updating the Booking Status Approved by Booking Id
@Operation(summary = "BOOKING STATUS APPROVED REST API", description = "REST API for Updating the Booking Status Approved by Booking Id")
// Updating the Booking Status Approved by Booking Id
@PostMapping("/updateBookingApproved/{bookingId}")
public ResponseEntity<BookingDetails> updateBookingApproved(
@PathVariable("bookingId") int bookingId,
@RequestParam("status") BookingDetails.BookingStatus status,
@RequestParam("comments") String comments) {
BookingDetails updatedBooking = bookingService.updateBookingStatus(bookingId, status, comments);
String adminname = (String) session.getAttribute("usertype");
Integer loginid = (Integer) session.getAttribute("id");
ApplicationLogs logs=new ApplicationLogs();
logs.setComments("Action by " + adminname);
logs.setLoginId(loginid);
logs.setBookingId(bookingId);
logs.setLogType("Booking Status:-"+status.toString());
InetAddress inetAddress;
@PathVariable("bookingId") int bookingId,
@RequestParam("status") BookingDetails.BookingStatus status,
@RequestParam("comments") String comments) {
BookingDetails updatedBooking = bookingService.updateBookingStatus(bookingId, status, comments);
String adminname = (String) session.getAttribute("usertype");
Integer loginid = (Integer) session.getAttribute("id");
ApplicationLogs logs = new ApplicationLogs();
logs.setComments("Action by " + adminname);
logs.setLoginId(loginid);
logs.setBookingId(bookingId);
logs.setLogType("Booking Status:-" + status.toString());
InetAddress inetAddress;
try {
inetAddress = InetAddress.getLocalHost();
String hostname = InetAddress.getLocalHost().getHostName();
logs.setIpaddress(inetAddress.getHostAddress());
logs.setSystemName(hostname);
String hostname = InetAddress.getLocalHost().getHostName();
logs.setIpaddress(inetAddress.getHostAddress());
logs.setSystemName(hostname);
} catch (UnknownHostException e) {
e.printStackTrace();
}
applicationLogsRepository.save(logs);
if (updatedBooking != null) {
return new ResponseEntity<>(updatedBooking, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
if (updatedBooking != null) {
return new ResponseEntity<>(updatedBooking, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
//ak
// ak
@PostMapping("/toggleStatus")
public ResponseEntity<String> toggleUserStatus(
@RequestParam Integer userId,
@RequestParam boolean active
) {
//System.out.println("userID: " + userId + ", active or deactivate: " + active);
try {
userService.toggleUserStatus(userId, active);
return ResponseEntity.ok("User status updated successfully");
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to update user status");
}
@RequestParam Integer userId,
@RequestParam boolean active) {
// System.out.println("userID: " + userId + ", active or deactivate: " +
// active);
try {
userService.toggleUserStatus(userId, active);
return ResponseEntity.ok("User status updated successfully");
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to update user status");
}
}
@Operation(
summary = "BOOKING STATUS REJECTED REST API",
description = "REST API for Updating the Booking Status Rejected by Booking Id"
)
//Updating the Booking Status Rejected by Booking Id
@Operation(summary = "BOOKING STATUS REJECTED REST API", description = "REST API for Updating the Booking Status Rejected by Booking Id")
// Updating the Booking Status Rejected by Booking Id
@PostMapping("/updateBookingReject/{bookingId}")
public ResponseEntity<?> updateBookingReject(
@PathVariable("bookingId") int bookingId,
@RequestParam("status") BookingDetails.BookingStatus status,
@RequestParam("comments") String comments,
@RequestParam("reasontype") int reasontype) {
if (reasontype == 1) {
Optional<BookingDetails> book=bookingDetailsRepository.findById(bookingId);
BookingDetails result=book.get();
result.setBookingStatus(BookingStatus.REJECTED);
result.setRefundStatus(RefundStatus.NA);
List<BookingCalendar> bookingCalendarList = bookingCalendarRepository.getCancellingdata1(String.valueOf(result.getBookingId()));
for (BookingCalendar calendar : bookingCalendarList) {
boolean isUpdated = false;
if (String.valueOf(result.getBookingId()).equals(calendar.getBookingId_1())) {
calendar.setBookingId_1(null);
isUpdated = true;
}
if (String.valueOf(result.getBookingId()).equals(calendar.getBookingId_2())) {
calendar.setBookingId_2(null);
isUpdated = true;
}
if (calendar.isMorningSlot()) {
calendar.setMorningSlot(false);
isUpdated = true;
}
if (calendar.isEveningSlot()) {
calendar.setEveningSlot(false);
isUpdated = true;
}
if (isUpdated) {
calendar.setIs_delete(true);
bookingCalendarRepository.save(calendar);
}
}
bookingDetailsRepository.save(result);
String adminname = (String) session.getAttribute("usertype");
Integer loginid = (Integer) session.getAttribute("id");
ApplicationLogs logs=new ApplicationLogs();
logs.setComments("Action by " + adminname);
logs.setLoginId(loginid);
logs.setBookingId(bookingId);
logs.setLogType("Booking Status:-"+status.toString());
InetAddress inetAddress;
@PathVariable("bookingId") int bookingId,
@RequestParam("status") BookingDetails.BookingStatus status,
@RequestParam("comments") String comments,
@RequestParam("reasontype") int reasontype) {
if (reasontype == 1) {
Optional<BookingDetails> book = bookingDetailsRepository.findById(bookingId);
BookingDetails result = book.get();
result.setBookingStatus(BookingStatus.REJECTED);
result.setRefundStatus(RefundStatus.NA);
List<BookingCalendar> bookingCalendarList = bookingCalendarRepository
.getCancellingdata1(String.valueOf(result.getBookingId()));
for (BookingCalendar calendar : bookingCalendarList) {
boolean isUpdated = false;
if (String.valueOf(result.getBookingId()).equals(calendar.getBookingId_1())) {
calendar.setBookingId_1(null);
isUpdated = true;
}
if (String.valueOf(result.getBookingId()).equals(calendar.getBookingId_2())) {
calendar.setBookingId_2(null);
isUpdated = true;
}
if (calendar.isMorningSlot()) {
calendar.setMorningSlot(false);
isUpdated = true;
}
if (calendar.isEveningSlot()) {
calendar.setEveningSlot(false);
isUpdated = true;
}
if (isUpdated) {
calendar.setIs_delete(true);
bookingCalendarRepository.save(calendar);
}
}
bookingDetailsRepository.save(result);
String adminname = (String) session.getAttribute("usertype");
Integer loginid = (Integer) session.getAttribute("id");
ApplicationLogs logs = new ApplicationLogs();
logs.setComments("Action by " + adminname);
logs.setLoginId(loginid);
logs.setBookingId(bookingId);
logs.setLogType("Booking Status:-" + status.toString());
InetAddress inetAddress;
try {
inetAddress = InetAddress.getLocalHost();
String hostname = InetAddress.getLocalHost().getHostName();
logs.setIpaddress(inetAddress.getHostAddress());
logs.setSystemName(hostname);
String hostname = InetAddress.getLocalHost().getHostName();
logs.setIpaddress(inetAddress.getHostAddress());
logs.setSystemName(hostname);
} catch (UnknownHostException e) {
e.printStackTrace();
}
return ResponseEntity.ok(result);
} else if (reasontype == 2) {
BookingDetails rejectBooking = bookingService.updateCancelledBookingStatus(bookingId, status, comments);
Optional<BookingDetails> book=bookingDetailsRepository.findById(bookingId);
BookingDetails bookingDetails=book.get();
String rejectionsms="Your booking ID "+bookingDetails.getBookingId()+" on "+bookingDetails.getStartDate()+" has been rejected by GCC due to insufficient details.";
String rejectedurlString ="https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to="+bookingDetails.getUsers().getMobileNo()+"&from=GCCCRP&body="+rejectionsms+"&entityid=1401572690000011081&templateid=1407172346485956648";
//String rejectedwhatsupmsg="https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to="+bookingDetails.getUsers().getMobileNo()+"&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+booking+with+ID+"+bookingId+"+on+"+bookingDetails.getStartDate()+"+has+been+rejected+by+GCC+due+to+insufficient+details.+%0AThanks+for+using+GCC+Community+Hall+Booking+System.";
String rejectedwhatsupmsg="https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to="+bookingDetails.getUsers().getMobileNo()+"&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+booking+with+ID+"+bookingId+"+on+"+bookingDetails.getStartDate()+"+has+been+rejected+by+GCC+due+to+insufficient+details.";
return ResponseEntity.ok(result);
} else if (reasontype == 2) {
BookingDetails rejectBooking = bookingService.updateCancelledBookingStatus(bookingId, status, comments);
Optional<BookingDetails> book = bookingDetailsRepository.findById(bookingId);
BookingDetails bookingDetails = book.get();
String rejectionsms = "Your booking ID " + bookingDetails.getBookingId() + " on "
+ bookingDetails.getStartDate() + " has been rejected by GCC due to insufficient details.";
String rejectedurlString = "https://tmegov.onex-aura.com/api/sms?key=pfTEYN6H&to="
+ bookingDetails.getUsers().getMobileNo() + "&from=GCCCRP&body=" + rejectionsms
+ "&entityid=1401572690000011081&templateid=1407172346485956648";
// String
// rejectedwhatsupmsg="https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to="+bookingDetails.getUsers().getMobileNo()+"&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+booking+with+ID+"+bookingId+"+on+"+bookingDetails.getStartDate()+"+has+been+rejected+by+GCC+due+to+insufficient+details.+%0AThanks+for+using+GCC+Community+Hall+Booking+System.";
String rejectedwhatsupmsg = "https://media.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ&send_to="
+ bookingDetails.getUsers().getMobileNo()
+ "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=Your+booking+with+ID+" + bookingId
+ "+on+" + bookingDetails.getStartDate() + "+has+been+rejected+by+GCC+due+to+insufficient+details.";
whatsappMsgServiceImpl.sendMsg(rejectedwhatsupmsg);
whatsappMsgServiceImpl.sendSMS(rejectedurlString);
String adminname = (String) session.getAttribute("usertype");
Integer loginid = (Integer) session.getAttribute("id");
ApplicationLogs logs=new ApplicationLogs();
logs.setComments("Action by " + adminname);
logs.setLoginId(loginid);
logs.setBookingId(bookingId);
logs.setLogType("Booking Status:-"+status.toString());
InetAddress inetAddress;
whatsappMsgServiceImpl.sendSMS(rejectedurlString);
String adminname = (String) session.getAttribute("usertype");
Integer loginid = (Integer) session.getAttribute("id");
ApplicationLogs logs = new ApplicationLogs();
logs.setComments("Action by " + adminname);
logs.setLoginId(loginid);
logs.setBookingId(bookingId);
logs.setLogType("Booking Status:-" + status.toString());
InetAddress inetAddress;
try {
inetAddress = InetAddress.getLocalHost();
String hostname = InetAddress.getLocalHost().getHostName();
logs.setIpaddress(inetAddress.getHostAddress());
logs.setSystemName(hostname);
String hostname = InetAddress.getLocalHost().getHostName();
logs.setIpaddress(inetAddress.getHostAddress());
logs.setSystemName(hostname);
} catch (UnknownHostException e) {
e.printStackTrace();
}
applicationLogsRepository.save(logs);
return ResponseEntity.ok(rejectBooking);
} else {
return ResponseEntity.badRequest().body("Invalid reasontype");
}
return ResponseEntity.ok(rejectBooking);
} else {
return ResponseEntity.badRequest().body("Invalid reasontype");
}
}
@Operation(
summary = "Retrieving BOOKING STATUS APPROVED REST API",
description = "REST API for retrieving the Booking Status Approved"
)
//retrieving the Booking Status Approved
@Operation(summary = "Retrieving BOOKING STATUS APPROVED REST API", description = "REST API for retrieving the Booking Status Approved")
// retrieving the Booking Status Approved
@GetMapping("/user-Approved")
public ResponseEntity<List<Users>> getUserApprovedList() {
List<Users> userApproved = usersRepository.getUserApproved();
return new ResponseEntity<>(userApproved, HttpStatus.OK);
}
@Operation(
summary = "Retrieving BOOKING STATUS REJECTED REST API",
description = "REST API for retrieving the Booking Status Rejected"
)
//retrieving the Booking Status Rejected
List<Users> userApproved = usersRepository.getUserApproved();
return new ResponseEntity<>(userApproved, HttpStatus.OK);
}
@Operation(summary = "Retrieving BOOKING STATUS REJECTED REST API", description = "REST API for retrieving the Booking Status Rejected")
// retrieving the Booking Status Rejected
@GetMapping("/user-Reject")
public ResponseEntity<List<Users>> getUserRejectedList() {
List<Users> userReject = usersRepository.getUserReject();
return new ResponseEntity<>(userReject, HttpStatus.OK);
}
@Operation(
summary = "Counter Refund Approval by Officer REST API",
description = "REST API to approve the Counter Refund by Officer"
)
//RefundApproval by Officer
@PostMapping("/approveRefund/{id}")
public ResponseEntity<String> approveRefund(@PathVariable int id) {
Optional<CounterRefundList> refundListOptional = counterRefundListRepository.findById(id);
if (refundListOptional.isPresent()) {
CounterRefundList refundList = refundListOptional.get();
refundList.setInitialisationStatus(CounterRefundList.InitialisationStatus.APPROVED);
counterRefundListRepository.save(refundList);
return new ResponseEntity<>("Refund with counterId " + id + " has been approved", HttpStatus.OK);
} else {
return new ResponseEntity<>("Refund with counterId " + id + " not found", HttpStatus.NOT_FOUND);
}
List<Users> userReject = usersRepository.getUserReject();
return new ResponseEntity<>(userReject, HttpStatus.OK);
}
@Operation(summary = "Counter Refund Approval by Officer REST API", description = "REST API to approve the Counter Refund by Officer")
// RefundApproval by Officer
@PostMapping("/approveRefund/{id}")
public ResponseEntity<String> approveRefund(@PathVariable int id) {
Optional<CounterRefundList> refundListOptional = counterRefundListRepository.findById(id);
if (refundListOptional.isPresent()) {
CounterRefundList refundList = refundListOptional.get();
refundList.setInitialisationStatus(CounterRefundList.InitialisationStatus.APPROVED);
counterRefundListRepository.save(refundList);
return new ResponseEntity<>("Refund with counterId " + id + " has been approved", HttpStatus.OK);
} else {
return new ResponseEntity<>("Refund with counterId " + id + " not found", HttpStatus.NOT_FOUND);
}
}
@Operation(
summary = "Counter Refund Reject by Officer REST API",
description = "REST API to Reject the Counter Refund by Officer"
)
//RefundReject by Officer
@PostMapping("/rejectRefund/{id}")
public ResponseEntity<String> rejectRefund(@PathVariable int id) {
Optional<CounterRefundList> rejectRefund = counterRefundListRepository.findById(id);
if (rejectRefund.isPresent()) {
CounterRefundList refundList = rejectRefund.get();
refundList.setInitialisationStatus(CounterRefundList.InitialisationStatus.REJECTED);
counterRefundListRepository.save(refundList);
return new ResponseEntity<>("Refund with counterId " + id + " has been approved", HttpStatus.OK);
} else {
return new ResponseEntity<>("Refund with counterId " + id + " not found", HttpStatus.NOT_FOUND);
}
@Operation(summary = "Counter Refund Reject by Officer REST API", description = "REST API to Reject the Counter Refund by Officer")
// RefundReject by Officer
@PostMapping("/rejectRefund/{id}")
public ResponseEntity<String> rejectRefund(@PathVariable int id) {
Optional<CounterRefundList> rejectRefund = counterRefundListRepository.findById(id);
if (rejectRefund.isPresent()) {
CounterRefundList refundList = rejectRefund.get();
refundList.setInitialisationStatus(CounterRefundList.InitialisationStatus.REJECTED);
counterRefundListRepository.save(refundList);
return new ResponseEntity<>("Refund with counterId " + id + " has been approved", HttpStatus.OK);
} else {
return new ResponseEntity<>("Refund with counterId " + id + " not found", HttpStatus.NOT_FOUND);
}
}
@Operation(
summary = "Reason By reasonName REST API",
description = "REST API to get the Reason Details with the reason"
)
//retrieving the Reason Details with the reason
@GetMapping("/getReasonByName")
public ResponseEntity<?> getReasonByName(@RequestParam String reasonName){
return ResponseEntity.ok(reasonMasterService.getReasonByName(reasonName));
}
@Operation(summary = "Reason By reasonName REST API", description = "REST API to get the Reason Details with the reason")
// retrieving the Reason Details with the reason
@GetMapping("/getReasonByName")
public ResponseEntity<?> getReasonByName(@RequestParam String reasonName) {
return ResponseEntity.ok(reasonMasterService.getReasonByName(reasonName));
}
@PostMapping("/uploadChallonDetails/{settlementId}")
public ResponseEntity<Settlement> updateApprovedSettlementStatus(
@PathVariable("settlementId") int settlementId,
@RequestParam(name = "ddNumber", required = false) Long ddNumber,
@RequestParam(name = "ddDate", required = false) String ddDate,
@RequestParam(name = "ddamount", required = false) Long ddamount,
@RequestParam(name = "challonnumber", required = false) Long challonnumber,
@RequestParam(name = "challonamount", required = false) Long challonamount,
@RequestParam(name = "challonimage") MultipartFile challonimage) {
// Add null checks and default values if necessary
Settlement settlement = settlementService.uploadChallonDetails(
settlementId,
ddNumber != null ? ddNumber : 0L,
ddDate,
ddamount != null ? ddamount : 0L,
challonimage,
challonnumber != null ? challonnumber : 0L,
challonamount != null ? challonamount : 0L);
if (settlement != null) {
return new ResponseEntity<>(settlement, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
@PathVariable("settlementId") int settlementId,
@RequestParam(name = "ddNumber", required = false) Long ddNumber,
@RequestParam(name = "ddDate", required = false) String ddDate,
@RequestParam(name = "ddamount", required = false) Long ddamount,
@RequestParam(name = "challonnumber", required = false) Long challonnumber,
@RequestParam(name = "challonamount", required = false) Long challonamount,
@RequestParam(name = "challonimage") MultipartFile challonimage) {
// Add null checks and default values if necessary
Settlement settlement = settlementService.uploadChallonDetails(
settlementId,
ddNumber != null ? ddNumber : 0L,
ddDate,
ddamount != null ? ddamount : 0L,
challonimage,
challonnumber != null ? challonnumber : 0L,
challonamount != null ? challonamount : 0L);
if (settlement != null) {
return new ResponseEntity<>(settlement, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@PostMapping("/approveCancelledBookingRefund/{bookingId}")
public ResponseEntity<String> updateCancelledRefundStatus(
@PathVariable("bookingId") int bookingId,
@RequestParam("status") BookingDetails.RefundStatus status) {
try {
// Update refund status preliminarily
// //BookingDetails updatedBooking = bookingService.updateRefundStatus(bookingId, status);
// if (updatedBooking == null) {
// return new ResponseEntity<>("Booking not found for ID: " + bookingId, HttpStatus.NOT_FOUND);
// }
// Log the action
String adminName = (String) session.getAttribute("usertype");
Integer loginId = (Integer) session.getAttribute("id");
ApplicationLogs logs = new ApplicationLogs();
logs.setComments("Action by " + adminName);
logs.setLoginId(loginId);
logs.setBookingId(bookingId);
logs.setLogType("Settlement Approve: " + status.toString());
try {
InetAddress inetAddress = InetAddress.getLocalHost();
String hostname = InetAddress.getLocalHost().getHostName();
logs.setIpaddress(inetAddress.getHostAddress());
logs.setSystemName(hostname);
} catch (UnknownHostException e) {
e.printStackTrace();
}
applicationLogsRepository.save(logs);
// Process refund and adjust refund status accordingly
String refundResponse = bookingServiceImpl.processRefundRequest(bookingId);
if (refundResponse.contains("successful")) {
// Refund success: leave refund status as updated
return new ResponseEntity<>(refundResponse, HttpStatus.OK);
} else {
// Refund failure: update refund status to FAILURE
bookingService.updateRefundStatus(bookingId, BookingDetails.RefundStatus.FAILURE);
return new ResponseEntity<>(refundResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
} catch (Exception e) {
return new ResponseEntity<>("An error occurred while processing the refund for Booking ID: " + bookingId, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@PathVariable("bookingId") int bookingId,
@RequestParam("status") BookingDetails.RefundStatus status) {
try {
// Update refund status preliminarily
// //BookingDetails updatedBooking =
// bookingService.updateRefundStatus(bookingId, status);
// if (updatedBooking == null) {
// return new ResponseEntity<>("Booking not found for ID: " + bookingId,
// HttpStatus.NOT_FOUND);
// }
// Log the action
String adminName = (String) session.getAttribute("usertype");
Integer loginId = (Integer) session.getAttribute("id");
ApplicationLogs logs = new ApplicationLogs();
logs.setComments("Action by " + adminName);
logs.setLoginId(loginId);
logs.setBookingId(bookingId);
logs.setLogType("Settlement Approve: " + status.toString());
@GetMapping("/bookingstatistics")
public ResponseEntity<Map<String, Map<String, Integer>>> getBookingStatistics(
@RequestParam (required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate fromDate,
@RequestParam (required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate toDate,
HttpSession session,
@RequestParam(required = false) String division,
@RequestParam(required=false, defaultValue = "1000") Integer hallid,
@RequestParam(required = false) String userType) {
try {
InetAddress inetAddress = InetAddress.getLocalHost();
String hostname = InetAddress.getLocalHost().getHostName();
logs.setIpaddress(inetAddress.getHostAddress());
logs.setSystemName(hostname);
} catch (UnknownHostException e) {
e.printStackTrace();
}
applicationLogsRepository.save(logs);
// Process refund and adjust refund status accordingly
String refundResponse = bookingServiceImpl.processRefundRequest(bookingId);
if (refundResponse.contains("successful")) {
// Refund success: leave refund status as updated
return new ResponseEntity<>(refundResponse, HttpStatus.OK);
} else {
// Refund failure: update refund status to FAILURE
bookingService.updateRefundStatus(bookingId, BookingDetails.RefundStatus.FAILURE);
return new ResponseEntity<>(refundResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
} catch (Exception e) {
return new ResponseEntity<>("An error occurred while processing the refund for Booking ID: " + bookingId,
HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@GetMapping("/bookingstatistics")
public ResponseEntity<Map<String, Map<String, Integer>>> getBookingStatistics(
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate fromDate,
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate toDate,
HttpSession session,
@RequestParam(required = false) String division,
@RequestParam(required = false, defaultValue = "1000") Integer hallid,
@RequestParam(required = false) String userType) {
String zone = (String) session.getAttribute("zone");
Map<String, Map<String, Integer>> statistics = bookingService.getOfficerDashboard(fromDate, toDate, zone, division, hallid, userType);
return ResponseEntity.ok(statistics);
Map<String, Map<String, Integer>> statistics = bookingService.getOfficerDashboard(fromDate, toDate, zone,
division, hallid, userType);
return ResponseEntity.ok(statistics);
}
@GetMapping("/getHallsDetailsByZone")
public ResponseEntity<Map<String, Object>> getHallsDetailsByZone(@RequestParam String zone)
{
public ResponseEntity<Map<String, Object>> getHallsDetailsByZone(@RequestParam String zone) {
Map<String, Object> hallzones=hallDetailService.getHallsDetailsForOfficer(zone);
return ResponseEntity.ok(hallzones);
}
Map<String, Object> hallzones = hallDetailService.getHallsDetailsForOfficer(zone);
return ResponseEntity.ok(hallzones);
}
@GetMapping("/byhallid")
public ResponseEntity<List<Map<String, Object>>> getBookingDetailsByHallId(@RequestParam int hallId) {
List<Map<String, Object>> bookingDetails = bookingService.getHallDetailsForOfficer(hallId);
return ResponseEntity.ok(bookingDetails);
}
public ResponseEntity<List<Map<String, Object>>> getBookingDetailsByHallId(@RequestParam int hallId) {
List<Map<String, Object>> bookingDetails = bookingService.getHallDetailsForOfficer(hallId);
return ResponseEntity.ok(bookingDetails);
}
//gccapps
// gccapps
@GetMapping("/getApprovedBookingDetails")
public List<BookingDetails> getApprovedBookingDetails() {
return bookingService.getApprovedBookingDetails();
}
public List<BookingDetails> getApprovedBookingDetails() {
return bookingService.getApprovedBookingDetails();
}
@GetMapping("/getRejectedBookingDetails")
public List<BookingDetails> getRejectedBookingDetails() {
return bookingService.getRejectedBookingDetails();
}
public List<BookingDetails> getRejectedBookingDetails() {
return bookingService.getRejectedBookingDetails();
}
@GetMapping("/getwaitingforNOCapproval")
public List<BookingDetails> getWaitingforNOCapproval() {
return bookingService.getWaitingforNOCapproval();
}
public List<BookingDetails> getWaitingforNOCapproval() {
return bookingService.getWaitingforNOCapproval();
}
@GetMapping("/getAllPaymentList")
public List<PaymentsDTO> getAllPaymentList() {
return paymentsService.getAllPaymentDetails();
}
public List<PaymentsDTO> getAllPaymentList() {
return paymentsService.getAllPaymentDetails();
}
}

207
src/main/java/com/gcc/communityHall/entity/HallRequestDetails.java

@ -0,0 +1,207 @@
package com.gcc.communityHall.entity;
import jakarta.persistence.*;
import java.time.LocalDateTime;
@Entity
@Table(name = "hall_request_details")
public class HallRequestDetails {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "req_id")
private Integer reqId;
@Column(name = "booking_id")
private Integer bookingId;
@Column(name = "start_date")
private String startDate;
@Column(name = "end_date")
private String endDate;
@Column(name = "starting_slot")
private Integer startingSlot;
@Column(name = "ending_slot")
private Integer endingSlot;
@Column(name = "reason")
private String reason;
@Column(name = "booking_status")
private String bookingStatus;
@Column(name = "hall_id")
private Integer hallId;
@Column(name = "user_id")
private Integer userId;
@Column(name = "org_type", length = 15)
private String orgType;
@Column(name = "event_description")
private String eventDescription;
@Column(name = "office_details")
private String officeDetails;
@Column(name = "bonafide_path")
private String bonafidePath;
@Column(name = "cdate", insertable = false, updatable = false)
private LocalDateTime cdate;
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private BookingDetails bookingDetails;
// @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private Users users;
// @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
// private HallDetails hallDetails;
// Getters and Setters
public Integer getReqId() {
return reqId;
}
public void setReqId(Integer reqId) {
this.reqId = reqId;
}
public String getStartDate() {
return startDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public Integer getStartingSlot() {
return startingSlot;
}
public void setStartingSlot(Integer startingSlot) {
this.startingSlot = startingSlot;
}
public Integer getEndingSlot() {
return endingSlot;
}
public void setEndingSlot(Integer endingSlot) {
this.endingSlot = endingSlot;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public String getBookingStatus() {
return bookingStatus;
}
public void setBookingStatus(String bookingStatus) {
this.bookingStatus = bookingStatus;
}
public Integer getHallId() {
return hallId;
}
public void setHallId(Integer hallId) {
this.hallId = hallId;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getOrgType() {
return orgType;
}
public void setOrgType(String orgType) {
this.orgType = orgType;
}
public String getEventDescription() {
return eventDescription;
}
public void setEventDescription(String eventDescription) {
this.eventDescription = eventDescription;
}
public String getOfficeDetails() {
return officeDetails;
}
public void setOfficeDetails(String officeDetails) {
this.officeDetails = officeDetails;
}
public String getBonafidePath() {
return bonafidePath;
}
public void setBonafidePath(String bonafidePath) {
this.bonafidePath = bonafidePath;
}
public LocalDateTime getCdate() {
return cdate;
}
// public Users getUsers() {
// return users;
// }
// public void setUsers(Users users) {
// this.users = users;
// }
// public HallDetails getHallDetails() {
// return hallDetails;
// }
// public void setHallDetails(HallDetails hallDetails) {
// this.hallDetails = hallDetails;
// }
public Integer getBookingId() {
return bookingId;
}
public void setBookingId(Integer bookingId) {
this.bookingId = bookingId;
}
public BookingDetails getBookingDetails() {
return bookingDetails;
}
public void setBookingDetails(BookingDetails bookingDetails) {
this.bookingDetails = bookingDetails;
}
}

45
src/main/java/com/gcc/communityHall/entity/ReasonMaster.java

@ -23,7 +23,10 @@ public class ReasonMaster {
private String updatedBy;
private int maxdays;
@OneToMany(mappedBy = "reasonMaster",fetch = FetchType.LAZY,cascade = CascadeType.ALL)
private boolean isActive;
private boolean isDelete;
@OneToMany(mappedBy = "reasonMaster", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List<ReasonDocumentMaster> reasonDocumentMasterList;
public int getReasonId() {
@ -66,20 +69,36 @@ public class ReasonMaster {
this.reasonDocumentMasterList = reasonDocumentMasterList;
}
public int getMaxdays() {
return maxdays;
}
public int getMaxdays() {
return maxdays;
}
public void setMaxdays(int maxdays) {
this.maxdays = maxdays;
}
public void setMaxdays(int maxdays) {
this.maxdays = maxdays;
}
public String getReasoncode() {
return reasoncode;
}
public String getReasoncode() {
return reasoncode;
}
public void setReasoncode(String reasoncode) {
this.reasoncode = reasoncode;
}
public void setReasoncode(String reasoncode) {
this.reasoncode = reasoncode;
}
public void setActive(boolean isActive) {
this.isActive = isActive;
}
public boolean getActive() {
return isActive;
}
public void setDelete(boolean isDelete) {
this.isDelete = isDelete;
}
public boolean getDelete() {
return isDelete;
}
}

11
src/main/java/com/gcc/communityHall/exception/PaymentRefundSlotOccupiedException.java

@ -9,15 +9,14 @@ import com.gcc.communityHall.service.Impl.BookingServiceImpl;
import com.gcc.communityHall.service.WhatsappMsgService;
import org.springframework.beans.factory.annotation.Autowired;
public class PaymentRefundSlotOccupiedException extends RuntimeException{
public class PaymentRefundSlotOccupiedException extends RuntimeException {
// @Autowired
// BookingService bookingService;
// @Autowired
// BookingService bookingService;
private String exMsg;
private String exMsg;
public PaymentRefundSlotOccupiedException(String exMsg){
public PaymentRefundSlotOccupiedException(String exMsg) {
super(exMsg);
}
}

778
src/main/java/com/gcc/communityHall/paymentService/controller/PaymentController.java

@ -41,11 +41,10 @@ import com.gcc.communityHall.service.UserService;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
@Controller
@RequestMapping("/victoriahallbooking/payment")
public class PaymentController {
//ak
// ak
@Autowired
private EncryptionUtil encryptionUtil;
@ -73,143 +72,32 @@ public class PaymentController {
@Autowired
private AppConfig appConfig;
// @Autowired
// private ErpPostDataRepository erpPostDataRepository;
// @Autowired
// private ErpPostDataRepository erpPostDataRepository;
@Autowired
private PaymentsService paymentsService;
//ak
@PostMapping(value = "/response")
public String response(Model model, @RequestParam(required = false) String msg) throws NoSuchAlgorithmException {
String salt = this.paymentConfig.getEncryptionKey();
String confirmToken = "";
String status = this.paymentConfig.getTransactionSuccessCode();
String[] res = msg.split("\\|");
String c = "";
TransactionResponse response = this.paymentService.getTransactionResponseByTxansactionId(res[3], "temp");
Payments payment = new Payments();
payment.setTransactionId(response.getTxansactionId());
double amount = 0;
// ------------------ PAYMENT STRING PROCESSING ------------------
for (int i = 0; i < res.length; i++) {
if (i == res.length - 1) {
c = c + salt;
confirmToken = res[i];
} else if (res[i].isEmpty()) {
c = c + "|";
} else if (res[i].equals("NA")) {
c = c + "NA|";
} else {
c = c + res[i] + "|";
}
if (i == 5) {
response.setTpslTxnId(res[i]);
response.setAmount(res[6]);
response.setTxansactionId(res[3]);
response.setDate(res[8]);
}
}
int bookingId = response.getBookingId();
try {
amount = Double.parseDouble(response.getAmount());
} catch (Exception e) {}
payment.setAmountReceived(amount);
payment.setPaymentStatus("Not Completed");
BookingDetails bookingsDetails = bookser.getBookingsById(bookingId); // JPA fetch
payment.setBookingDetails(bookingsDetails);
response.setResponse(msg);
response.setStatusCode(res[0]);
bookingsDetails.setPayments(payment);
payment.setCdate(new Date());
// save transaction response
transactionResRepo.save(response);
// =============================================================
// CASE 1: FAILURE - AMOUNT MISMATCH
// =============================================================
if (bookingsDetails.getAmountReceived() != amount) {
if(paymentService.generateToken(c).equals(confirmToken) && status.equals(res[0])){
payment.setPaymentStatus("Success");
bookingsDetails.setPayments(payment);
paymentRepo.save(payment);
// booking failure logic
bookser.bookingFailure(bookingsDetails, 1);
}
// Fetch OR Generate booking_ref_id
String refId = bookser.getBookingRefIdByBookingId(bookingId);
// encrypt bookingId (coworkspace logic)
String encryptedId = encryptionUtil.encrypt(String.valueOf(bookingId));
model.addAttribute("ref_id", refId);
model.addAttribute("encryptedId", encryptedId);
return "redirect:/victoriahallbooking/user/acknowledgement?ref_id=" + refId;
}
// =============================================================
// CASE 2: SUCCESS FLOW
// =============================================================
if (paymentService.generateToken(c).equals(confirmToken) && status.equals(res[0])) {
payment.setPaymentStatus("Success");
bookingsDetails.setPayments(payment);
paymentRepo.save(payment);
try {
bookser.confirmBooking(bookingId);
} catch (Exception e) {
// ignore
}
}
// 🔥 Fetch OR Generate booking_ref_id
String refId = bookser.getBookingRefIdByBookingId(bookingId);
// 🔐 Encrypt bookingId
String encryptedId = encryptionUtil.encrypt(String.valueOf(bookingId));
model.addAttribute("ref_id", refId);
model.addAttribute("encryptedId", encryptedId);
return "redirect:/victoriahallbooking/user/acknowledgement?ref_id=" + refId;
}
/* @PostMapping(value = "/response")
// ak
@PostMapping(value = "/response")
public String response(Model model, @RequestParam(required = false) String msg) throws NoSuchAlgorithmException {
String salt = this.paymentConfig.getEncryptionKey();
String confirmToken = "";
String status = this.paymentConfig.getTransactionSuccessCode();
String s = new String(msg);
String c = new String();
String res[] = s.split("\\|");
String[] res = msg.split("\\|");
String c = "";
TransactionResponse response = this.paymentService.getTransactionResponseByTxansactionId(res[3], "temp");
Payments payment = new Payments();
payment.setTransactionId(response.getTxansactionId());
double amount = 0;
// ------------------ PAYMENT STRING PROCESSING ------------------
for (int i = 0; i < res.length; i++) {
if (i == res.length - 1) {
c = c + salt;
confirmToken = res[i];
@ -225,178 +113,331 @@ public String response(Model model, @RequestParam(required = false) String msg)
response.setTpslTxnId(res[i]);
response.setAmount(res[6]);
response.setTxansactionId(res[3]);
//String[] tDate = res[8].split(" ");
response.setDate(res[8]);
}
}
int bookingId = response.getBookingId();
try {
amount = Double.parseDouble(response.getAmount());
} catch (Exception e) {
// TODO: handle exception
//System.out.println("payment Controller lineNo-67");
}
payment.setAmountReceived(amount);
payment.setPaymentStatus("Not Completed");
BookingDetails bookingsDetails = bookser.getBookingsById(bookingId);
BookingDetails bookingsDetails = bookser.getBookingsById(bookingId); // JPA fetch
payment.setBookingDetails(bookingsDetails);
response.setResponse(msg);
response.setStatusCode(res[0]);
bookingsDetails.setPayments(payment);
payment.setCdate(new Date());
System.out.println("bookingsDetails.getAmountReceived().." + bookingsDetails.getAmountReceived());
System.out.println("amount: " + amount);
// save transaction response
transactionResRepo.save(response);
TransactionResponse save = transactionResRepo.save(response);
// =============================================================
// CASE 1: FAILURE - AMOUNT MISMATCH
// =============================================================
if (bookingsDetails.getAmountReceived() != amount) {
if (bookingsDetails.getAmountReceived() != amount) { // Reject booking if the amount is incorrect
if(paymentService.generateToken(c).equals(confirmToken) && status.equals(res[0])){
if (paymentService.generateToken(c).equals(confirmToken) && status.equals(res[0])) {
payment.setPaymentStatus("Success");
bookingsDetails.setPayments(payment);
paymentRepo.save(payment);
// booking failure logic
bookser.bookingFailure(bookingsDetails, 1);
}
//ak
// Fetch OR Generate booking_ref_id
String refId = bookser.getBookingRefIdByBookingId(bookingId);
// encrypt bookingId (coworkspace logic)
String encryptedId = encryptionUtil.encrypt(String.valueOf(bookingId));
model.addAttribute("bookingsDetails", bookingsDetails);
return "redirect:/victoriahallbooking/user/acknowledgement?bookingId=" + bookingsDetails.getBookingId();
}
model.addAttribute("ref_id", refId);
model.addAttribute("encryptedId", encryptedId);
return "redirect:/victoriahallbooking/user/acknowledgement?ref_id=" + refId;
}
// =============================================================
// CASE 2: SUCCESS FLOW
// =============================================================
if (paymentService.generateToken(c).equals(confirmToken) && status.equals(res[0])) {
payment.setPaymentStatus("Success");
bookingsDetails.setPayments(payment);
try {
String confirmBooking = bookser.confirmBooking(response.getBookingId());
}catch (Exception e){
// return "redirect:/communityhall/user/acknowledgement?bookingId=" + bookingsDetails.getBookingId();
paymentRepo.save(payment);
try {
bookser.confirmBooking(bookingId);
} catch (Exception e) {
// ignore
}
// postDataToERP(payment, response); // post payment details to ERP
// System.out.println("\n confirmBooking:- paymentController 111"+confirmBooking+"\n");
// if(confirmBooking.equals("Booking confirmed successfully")) {
// //bookser.updateBookingStatusById(bookingsDetails.getBookingId(), BookingDetails.BookingStatus.APPROVED, "confirm");
// // String bookingconfimationsms = "Your booking with ID "+bookingsDetails.getBookingId()+" on" +bookingsDetails.getBookingId()+" has been successfully confirmed. Thanks for using GCC Community Hall Booking System.";
// }else if(confirmBooking.equals("Slot occupied")) {
//// System.out.println("Slot occupied line 115");
//// BookingDetails crrSts = bookser.updateBookingStatusById(bookingsDetails.getBookingId(), BookingDetails.BookingStatus.REFUNDED, "slot occupied Refund will happen shortly");
//// System.out.println("BookingDetails:-"+crrSts.getBookingStatus());
// }
// else if(confirmBooking.equals("Error confirming booking")) {
// bookser.updateBookingStatusById(bookingsDetails.getBookingId(), BookingDetails.BookingStatus.PENDING, "Error");
//
// }
}
// System.out.println(response.toString());
model.addAttribute("bookingsDetails", bookingsDetails); // Add single BookingDetails object
//System.out.println(save.toString());
paymentRepo.save(payment);
return "redirect:/victoriahallbooking/user/acknowledgement?bookingId=" + bookingsDetails.getBookingId();
}*/
/*public void postDataToERP(Payments payment, TransactionResponse res) {
RestTemplate restTemplate = new RestTemplate();
erpPostData erpData = new erpPostData();
SimpleDateFormat outputFormat = new SimpleDateFormat("dd/MM/yyyy");
String txDate = outputFormat.format(payment.getCdate());
String assesNo = LocalDate.now().getYear() + "/COMM/" + res.getBookingId();
Map<String, Object> data = new TreeMap<>();
*//*static mandatory input to be sent *//*
data.put("serviceId", "getOtherCollection");
data.put("COLLECTION_TYPE", "Community Hall");
data.put("TOTALTRANSACTIONCODE", "450310000");
// /end of static/
// /unique data to be send/
data.put("ASSESSMENTNO", assesNo);
data.put("UNIQUERECEIPTID", res.getBookingId());
data.put("TRANSACTIONNO", payment.getTransactionId());
data.put("TRANSACTIONREFNO", res.getTpslTxnId());
data.put("TRANSACTIONDATE", txDate); //payment date format dd/mm/yyyy -> 19/02/2025
data.put("TOTALTRANSACTIONAMOUNT", payment.getBookingDetails().getAmountReceived());
data.put("MSTRCODEONE", "061");
data.put("SPLITAMOUNTONE", payment.getBookingDetails().getHallAmount());
data.put("MSTRCODETWO", "062");
data.put("SPLITAMOUNTTWO", payment.getBookingDetails().getDepositAmount());
data.put("MSTRCODETHREE", "063");
data.put("SPLITAMOUNTTHREE", payment.getBookingDetails().getGst());
// /Amount Collected from party/
data.put("PARTYNAME", payment.getBookingDetails().getUsers().getName());
data.put("PARTYADDRESS", payment.getBookingDetails().getUsers().getStreet() + "," +
payment.getBookingDetails().getUsers().getArea() + "," + payment.getBookingDetails().getUsers().getLocation() + "," +
payment.getBookingDetails().getUsers().getPinCode());
data.put("PARTYMOBILE", payment.getBookingDetails().getUsers().getMobileNo());
*//* end *//*
System.out.println(data);
System.out.println(appConfig.getCommErpUrl());
// ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(appConfig.getErpUrl(), data, String.class);
// System.out.println(stringResponseEntity.getBody());
erpData.setTx_id(payment.getTransactionId());
erpData.setBooking_det_booking_id(res.getBookingId());
erpData.setStatus(true);
erpData.setCdate(LocalDate.now());
erpData.setPay_status(1);
erpPostDataRepository.save(erpData);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(appConfig.getCommErpUrl());
for (Map.Entry<String, Object> entry : data.entrySet()) {
builder.queryParam(entry.getKey(), entry.getValue());
}
String urlMsg = builder.toUriString();
System.out.println(urlMsg);
try {
HttpURLConnection connection = null;
URL url = new URL(urlMsg);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
// response=responseCode+"";
System.out.println("Response Code: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // 200 OK
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("Response: " + response.toString());
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(response.toString());
// 🔥 Fetch OR Generate booking_ref_id
String refId = bookser.getBookingRefIdByBookingId(bookingId);
String resultStatus = jsonNode.get("ResultStatus").asText();
// 🔐 Encrypt bookingId
String encryptedId = encryptionUtil.encrypt(String.valueOf(bookingId));
if (!resultStatus.isEmpty() && resultStatus.equals("false")) {
erpData.setStatus(false);
erpPostDataRepository.save(erpData);
}
model.addAttribute("ref_id", refId);
model.addAttribute("encryptedId", encryptedId);
} else {
System.out.println("GET request failed.");
}
return "redirect:/victoriahallbooking/user/acknowledgement?ref_id=" + refId;
}
} catch (Exception e) {
e.printStackTrace();
}
}*/
/*
* @PostMapping(value = "/response")
* public String response(Model model, @RequestParam(required = false) String
* msg) throws NoSuchAlgorithmException {
*
* String salt = this.paymentConfig.getEncryptionKey();
*
* String confirmToken = "";
* String status = this.paymentConfig.getTransactionSuccessCode();
* String s = new String(msg);
* String c = new String();
* String res[] = s.split("\\|");
*
* TransactionResponse response =
* this.paymentService.getTransactionResponseByTxansactionId(res[3], "temp");
* Payments payment = new Payments();
* payment.setTransactionId(response.getTxansactionId());
* double amount = 0;
*
*
* for (int i = 0; i < res.length; i++) {
* if (i == res.length - 1) {
* c = c + salt;
* confirmToken = res[i];
* } else if (res[i].isEmpty()) {
* c = c + "|";
* } else if (res[i].equals("NA")) {
* c = c + "NA|";
* } else {
* c = c + res[i] + "|";
* }
*
* if (i == 5) {
* response.setTpslTxnId(res[i]);
* response.setAmount(res[6]);
* response.setTxansactionId(res[3]);
* //String[] tDate = res[8].split(" ");
* response.setDate(res[8]);
* }
* }
* int bookingId = response.getBookingId();
* try {
* amount = Double.parseDouble(response.getAmount());
* } catch (Exception e) {
* // TODO: handle exception
* //System.out.println("payment Controller lineNo-67");
* }
* payment.setAmountReceived(amount);
* payment.setPaymentStatus("Not Completed");
*
* BookingDetails bookingsDetails = bookser.getBookingsById(bookingId);
* payment.setBookingDetails(bookingsDetails);
* response.setResponse(msg);
* response.setStatusCode(res[0]);
* bookingsDetails.setPayments(payment);
* payment.setCdate(new Date());
*
* System.out.println("bookingsDetails.getAmountReceived().." +
* bookingsDetails.getAmountReceived());
* System.out.println("amount: " + amount);
*
* TransactionResponse save = transactionResRepo.save(response);
*
* if (bookingsDetails.getAmountReceived() != amount) { // Reject booking if the
* amount is incorrect
* if(paymentService.generateToken(c).equals(confirmToken) &&
* status.equals(res[0])){
* payment.setPaymentStatus("Success");
* bookingsDetails.setPayments(payment);
* paymentRepo.save(payment);
* bookser.bookingFailure(bookingsDetails, 1);
* }
* //ak
*
*
*
* model.addAttribute("bookingsDetails", bookingsDetails);
* return "redirect:/victoriahallbooking/user/acknowledgement?bookingId=" +
* bookingsDetails.getBookingId();
* }
*
*
* if (paymentService.generateToken(c).equals(confirmToken) &&
* status.equals(res[0])) {
* payment.setPaymentStatus("Success");
* bookingsDetails.setPayments(payment);
* try {
* String confirmBooking = bookser.confirmBooking(response.getBookingId());
* }catch (Exception e){
* // return "redirect:/communityhall/user/acknowledgement?bookingId=" +
* bookingsDetails.getBookingId();
*
* }
* // postDataToERP(payment, response); // post payment details to ERP
* //
* System.out.println("\n confirmBooking:- paymentController 111"+confirmBooking
* +"\n");
* // if(confirmBooking.equals("Booking confirmed successfully")) {
* // //bookser.updateBookingStatusById(bookingsDetails.getBookingId(),
* BookingDetails.BookingStatus.APPROVED, "confirm");
* // // String bookingconfimationsms =
* "Your booking with ID "+bookingsDetails.getBookingId()+" on"
* +bookingsDetails.getBookingId()
* +" has been successfully confirmed. Thanks for using GCC Community Hall Booking System."
* ;
* // }else if(confirmBooking.equals("Slot occupied")) {
* //// System.out.println("Slot occupied line 115");
* //// BookingDetails crrSts =
* bookser.updateBookingStatusById(bookingsDetails.getBookingId(),
* BookingDetails.BookingStatus.REFUNDED,
* "slot occupied Refund will happen shortly");
* //// System.out.println("BookingDetails:-"+crrSts.getBookingStatus());
* // }
* // else if(confirmBooking.equals("Error confirming booking")) {
* // bookser.updateBookingStatusById(bookingsDetails.getBookingId(),
* BookingDetails.BookingStatus.PENDING, "Error");
* //
* // }
*
* }
*
* // System.out.println(response.toString());
* model.addAttribute("bookingsDetails", bookingsDetails); // Add single
* BookingDetails object
* //System.out.println(save.toString());
* paymentRepo.save(payment);
* return "redirect:/victoriahallbooking/user/acknowledgement?bookingId=" +
* bookingsDetails.getBookingId();
* }
*/
/*
* public void postDataToERP(Payments payment, TransactionResponse res) {
* RestTemplate restTemplate = new RestTemplate();
* erpPostData erpData = new erpPostData();
*
* SimpleDateFormat outputFormat = new SimpleDateFormat("dd/MM/yyyy");
* String txDate = outputFormat.format(payment.getCdate());
* String assesNo = LocalDate.now().getYear() + "/COMM/" + res.getBookingId();
*
* Map<String, Object> data = new TreeMap<>();
*//* static mandatory input to be sent *//*
* data.put("serviceId", "getOtherCollection");
* data.put("COLLECTION_TYPE", "Community Hall");
* data.put("TOTALTRANSACTIONCODE", "450310000");
* // /end of static/
* // /unique data to be send/
* data.put("ASSESSMENTNO", assesNo);
* data.put("UNIQUERECEIPTID", res.getBookingId());
* data.put("TRANSACTIONNO", payment.getTransactionId());
* data.put("TRANSACTIONREFNO", res.getTpslTxnId());
* data.put("TRANSACTIONDATE", txDate); //payment date format dd/mm/yyyy
* -> 19/02/2025
* data.put("TOTALTRANSACTIONAMOUNT",
* payment.getBookingDetails().getAmountReceived());
*
* data.put("MSTRCODEONE", "061");
* data.put("SPLITAMOUNTONE",
* payment.getBookingDetails().getHallAmount());
* data.put("MSTRCODETWO", "062");
* data.put("SPLITAMOUNTTWO",
* payment.getBookingDetails().getDepositAmount());
* data.put("MSTRCODETHREE", "063");
* data.put("SPLITAMOUNTTHREE", payment.getBookingDetails().getGst());
* // /Amount Collected from party/
* data.put("PARTYNAME",
* payment.getBookingDetails().getUsers().getName());
* data.put("PARTYADDRESS",
* payment.getBookingDetails().getUsers().getStreet() + "," +
* payment.getBookingDetails().getUsers().getArea() + "," +
* payment.getBookingDetails().getUsers().getLocation() + "," +
* payment.getBookingDetails().getUsers().getPinCode());
* data.put("PARTYMOBILE",
* payment.getBookingDetails().getUsers().getMobileNo());
*//* end *//*
* System.out.println(data);
* System.out.println(appConfig.getCommErpUrl());
* // ResponseEntity<String> stringResponseEntity =
* restTemplate.postForEntity(appConfig.getErpUrl(), data,
* String.class);
* // System.out.println(stringResponseEntity.getBody());
*
* erpData.setTx_id(payment.getTransactionId());
* erpData.setBooking_det_booking_id(res.getBookingId());
* erpData.setStatus(true);
* erpData.setCdate(LocalDate.now());
* erpData.setPay_status(1);
* erpPostDataRepository.save(erpData);
*
* UriComponentsBuilder builder =
* UriComponentsBuilder.fromHttpUrl(appConfig.getCommErpUrl())
* ;
* for (Map.Entry<String, Object> entry : data.entrySet()) {
* builder.queryParam(entry.getKey(), entry.getValue());
* }
*
* String urlMsg = builder.toUriString();
* System.out.println(urlMsg);
*
* try {
* HttpURLConnection connection = null;
*
* URL url = new URL(urlMsg);
* connection = (HttpURLConnection) url.openConnection();
* connection.setRequestMethod("GET");
*
* int responseCode = connection.getResponseCode();
* // response=responseCode+"";
* System.out.println("Response Code: " + responseCode);
*
* if (responseCode == HttpURLConnection.HTTP_OK) { // 200 OK
* BufferedReader in = new BufferedReader(new
* InputStreamReader(connection.getInputStream()));
* String inputLine;
* StringBuilder response = new StringBuilder();
* while ((inputLine = in.readLine()) != null) {
* response.append(inputLine);
* }
* in.close();
* System.out.println("Response: " + response.toString());
*
* ObjectMapper objectMapper = new ObjectMapper();
* JsonNode jsonNode =
* objectMapper.readTree(response.toString());
*
* String resultStatus =
* jsonNode.get("ResultStatus").asText();
*
* if (!resultStatus.isEmpty() &&
* resultStatus.equals("false")) {
* erpData.setStatus(false);
* erpPostDataRepository.save(erpData);
* }
*
* } else {
* System.out.println("GET request failed.");
* }
*
* } catch (Exception e) {
* e.printStackTrace();
* }
* }
*/
@PostMapping(value = "/additionaldamage-response")
public String additionaldamagePaymentresponse(Model model, @RequestParam(required = false) String msg) throws NoSuchAlgorithmException {
public String additionaldamagePaymentresponse(Model model, @RequestParam(required = false) String msg)
throws NoSuchAlgorithmException {
String salt = this.paymentConfig.getEncryptionKey();
@ -411,7 +452,6 @@ public String response(Model model, @RequestParam(required = false) String msg)
payment.setTransactionId(response.getTxansactionId());
double amount = 0;
for (int i = 0; i < res.length; i++) {
if (i == res.length - 1) {
c = c + salt;
@ -428,7 +468,7 @@ public String response(Model model, @RequestParam(required = false) String msg)
response.setTpslTxnId(res[i]);
response.setAmount(res[6]);
response.setTxansactionId(res[3]);
//String[] tDate = res[8].split(" ");
// String[] tDate = res[8].split(" ");
response.setDate(res[8]);
}
}
@ -437,7 +477,7 @@ public String response(Model model, @RequestParam(required = false) String msg)
amount = Double.parseDouble(response.getAmount());
} catch (Exception e) {
// TODO: handle exception
//System.out.println("payment Controller lineNo-67");
// System.out.println("payment Controller lineNo-67");
}
payment.setAmountReceived(amount);
payment.setPaymentStatus("Not Completed");
@ -462,108 +502,128 @@ public String response(Model model, @RequestParam(required = false) String msg)
}
model.addAttribute("bookingsDetails", bookingsDetails);
extraPaymentsRepository.save(payment);
// postEPDataToERP(payment, response); //post extra payments details to ERP
// return "redirect:/communityhall/user/collectionpendingacknowledgement?bookingId=" + bookingsDetails.getBookingId();
return "redirect:/victoriahallbooking/user/collectionpendingacknowledgement?bookingId=" + bookingsDetails.getBookingId();
// postEPDataToERP(payment, response); //post extra payments details to ERP
// return
// "redirect:/communityhall/user/collectionpendingacknowledgement?bookingId=" +
// bookingsDetails.getBookingId();
return "redirect:/victoriahallbooking/user/collectionpendingacknowledgement?bookingId="
+ bookingsDetails.getBookingId();
}
/*public void postEPDataToERP(ExtraPayments payment, TransactionResponse res) {
RestTemplate restTemplate = new RestTemplate();
erpPostData erpData = new erpPostData();
SimpleDateFormat outputFormat = new SimpleDateFormat("dd/MM/yyyy");
String txDate = outputFormat.format(payment.getCdate());
String assesNo = LocalDate.now().getYear() + "/COMM/ED/" + res.getBookingId();
Map<String, Object> data = new TreeMap<>();
*//*static mandatory input to be sent *//*
data.put("serviceId", "getOtherCollection");
data.put("COLLECTION_TYPE", "Community Hall");
data.put("TOTALTRANSACTIONCODE", "450310000");
// /end of static/
// /unique data to be send/
data.put("ASSESSMENTNO", assesNo);
data.put("UNIQUERECEIPTID", res.getBookingId());
data.put("TRANSACTIONNO", payment.getTransactionId());
data.put("TRANSACTIONREFNO", res.getTpslTxnId());
data.put("TRANSACTIONDATE", txDate); //payment date format dd/mm/yyyy -> 19/02/2025
data.put("TOTALTRANSACTIONAMOUNT", payment.getAmountReceived());
data.put("MSTRCODEONE", "061");
data.put("SPLITAMOUNTONE", 0);
data.put("MSTRCODETWO", "062");
data.put("SPLITAMOUNTTWO", payment.getAmountReceived());
data.put("MSTRCODETHREE", "063");
data.put("SPLITAMOUNTTHREE", 0);
// /Amount Collected from party/
data.put("PARTYNAME", payment.getBookingDetails().getUsers().getName());
data.put("PARTYADDRESS", payment.getBookingDetails().getUsers().getStreet() + "," +
payment.getBookingDetails().getUsers().getArea() + "," + payment.getBookingDetails().getUsers().getLocation() + "," +
payment.getBookingDetails().getUsers().getPinCode());
data.put("PARTYMOBILE", payment.getBookingDetails().getUsers().getMobileNo());
*//* end *//*
System.out.println(data);
System.out.println(appConfig.getCommErpUrl());
// ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(appConfig.getErpUrl(), data, String.class);
// System.out.println(stringResponseEntity.getBody());
erpData.setTx_id(payment.getTransactionId());
erpData.setBooking_det_booking_id(res.getBookingId());
erpData.setStatus(true);
erpData.setCdate(LocalDate.now());
erpData.setPay_status(2);
erpPostDataRepository.save(erpData);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(appConfig.getCommErpUrl());
for (Map.Entry<String, Object> entry : data.entrySet()) {
builder.queryParam(entry.getKey(), entry.getValue());
}
String urlMsg = builder.toUriString();
System.out.println(urlMsg);
try {
HttpURLConnection connection = null;
URL url = new URL(urlMsg);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
// response=responseCode+"";
System.out.println("Response Code: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // 200 OK
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("Response: " + response.toString());
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(response.toString());
String resultStatus = jsonNode.get("ResultStatus").asText();
if (!resultStatus.isEmpty() && resultStatus.equals("false")) {
erpData.setStatus(false);
erpPostDataRepository.save(erpData);
}
} else {
System.out.println("GET request failed.");
}
} catch (Exception e) {
e.printStackTrace();
}
}*/
/*
* public void postEPDataToERP(ExtraPayments payment, TransactionResponse res) {
* RestTemplate restTemplate = new RestTemplate();
* erpPostData erpData = new erpPostData();
*
* SimpleDateFormat outputFormat = new SimpleDateFormat("dd/MM/yyyy");
* String txDate = outputFormat.format(payment.getCdate());
* String assesNo = LocalDate.now().getYear() + "/COMM/ED/" +
* res.getBookingId();
*
* Map<String, Object> data = new TreeMap<>();
*//* static mandatory input to be sent *//*
* data.put("serviceId", "getOtherCollection");
* data.put("COLLECTION_TYPE", "Community Hall");
* data.put("TOTALTRANSACTIONCODE", "450310000");
* // /end of static/
* // /unique data to be send/
* data.put("ASSESSMENTNO", assesNo);
* data.put("UNIQUERECEIPTID", res.getBookingId());
* data.put("TRANSACTIONNO", payment.getTransactionId());
* data.put("TRANSACTIONREFNO", res.getTpslTxnId());
* data.put("TRANSACTIONDATE", txDate); //payment date format dd/mm/yyyy
* -> 19/02/2025
* data.put("TOTALTRANSACTIONAMOUNT", payment.getAmountReceived());
*
* data.put("MSTRCODEONE", "061");
* data.put("SPLITAMOUNTONE", 0);
* data.put("MSTRCODETWO", "062");
* data.put("SPLITAMOUNTTWO", payment.getAmountReceived());
* data.put("MSTRCODETHREE", "063");
* data.put("SPLITAMOUNTTHREE", 0);
* // /Amount Collected from party/
* data.put("PARTYNAME",
* payment.getBookingDetails().getUsers().getName());
* data.put("PARTYADDRESS",
* payment.getBookingDetails().getUsers().getStreet() + "," +
* payment.getBookingDetails().getUsers().getArea() + "," +
* payment.getBookingDetails().getUsers().getLocation() + "," +
* payment.getBookingDetails().getUsers().getPinCode());
* data.put("PARTYMOBILE",
* payment.getBookingDetails().getUsers().getMobileNo());
*//* end *//*
* System.out.println(data);
* System.out.println(appConfig.getCommErpUrl());
* // ResponseEntity<String> stringResponseEntity =
* restTemplate.postForEntity(appConfig.getErpUrl(), data,
* String.class);
* // System.out.println(stringResponseEntity.getBody());
*
* erpData.setTx_id(payment.getTransactionId());
* erpData.setBooking_det_booking_id(res.getBookingId());
* erpData.setStatus(true);
* erpData.setCdate(LocalDate.now());
* erpData.setPay_status(2);
* erpPostDataRepository.save(erpData);
*
* UriComponentsBuilder builder =
* UriComponentsBuilder.fromHttpUrl(appConfig.getCommErpUrl())
* ;
* for (Map.Entry<String, Object> entry : data.entrySet()) {
* builder.queryParam(entry.getKey(), entry.getValue());
* }
*
* String urlMsg = builder.toUriString();
* System.out.println(urlMsg);
*
* try {
* HttpURLConnection connection = null;
*
* URL url = new URL(urlMsg);
* connection = (HttpURLConnection) url.openConnection();
* connection.setRequestMethod("GET");
*
* int responseCode = connection.getResponseCode();
* // response=responseCode+"";
* System.out.println("Response Code: " + responseCode);
*
* if (responseCode == HttpURLConnection.HTTP_OK) { // 200 OK
* BufferedReader in = new BufferedReader(new
* InputStreamReader(connection.getInputStream()));
* String inputLine;
* StringBuilder response = new StringBuilder();
* while ((inputLine = in.readLine()) != null) {
* response.append(inputLine);
* }
* in.close();
* System.out.println("Response: " + response.toString());
*
* ObjectMapper objectMapper = new ObjectMapper();
* JsonNode jsonNode =
* objectMapper.readTree(response.toString());
*
* String resultStatus =
* jsonNode.get("ResultStatus").asText();
*
* if (!resultStatus.isEmpty() &&
* resultStatus.equals("false")) {
* erpData.setStatus(false);
* erpPostDataRepository.save(erpData);
* }
*
* } else {
* System.out.println("GET request failed.");
* }
*
* } catch (Exception e) {
* e.printStackTrace();
* }
* }
*/
@PostMapping(value = "/updatetransaction")
public String updatetransaction(Model model, @RequestParam(required = false) String txansactionId, @RequestParam(required = false) String msg) throws NoSuchAlgorithmException {
public String updatetransaction(Model model, @RequestParam(required = false) String txansactionId,
@RequestParam(required = false) String msg) throws NoSuchAlgorithmException {
Optional<TransactionResponse> transactionresponse = transactionResRepo.findByTxansactionId(txansactionId);
TransactionResponse transactionres = transactionresponse.get();
@ -581,7 +641,6 @@ public String response(Model model, @RequestParam(required = false) String msg)
payment.setTransactionId(response.getTxansactionId());
double amount = 0;
for (int i = 0; i < res.length; i++) {
if (i == res.length - 1) {
c = c + salt;
@ -598,7 +657,7 @@ public String response(Model model, @RequestParam(required = false) String msg)
response.setTpslTxnId(res[i]);
response.setAmount(res[6]);
response.setTxansactionId(res[3]);
//String[] tDate = res[8].split(" ");
// String[] tDate = res[8].split(" ");
response.setDate(res[8]);
}
}
@ -607,7 +666,7 @@ public String response(Model model, @RequestParam(required = false) String msg)
amount = Double.parseDouble(response.getAmount());
} catch (Exception e) {
// TODO: handle exception
//System.out.println("payment Controller lineNo-67");
// System.out.println("payment Controller lineNo-67");
}
payment.setAmountReceived(amount);
payment.setPaymentStatus("Not Completed");
@ -630,7 +689,7 @@ public String response(Model model, @RequestParam(required = false) String msg)
// System.out.println(response.toString());
model.addAttribute("bookingsDetails", bookingsDetails); // Add single BookingDetails object
//System.out.println(save.toString());
// System.out.println(save.toString());
paymentRepo.save(payment);
return "success";
} else {
@ -639,7 +698,8 @@ public String response(Model model, @RequestParam(required = false) String msg)
}
@PostMapping(value = "/refundcompleted")
public String refundCompleted(Model model, @RequestParam String txansactionId, @RequestParam(required = false) String msg) throws NoSuchAlgorithmException {
public String refundCompleted(Model model, @RequestParam String txansactionId,
@RequestParam(required = false) String msg) throws NoSuchAlgorithmException {
Optional<TransactionResponse> transactionresponse = transactionResRepo.findByTxansactionId(txansactionId);
if (transactionresponse.isPresent()) {
TransactionResponse transactionres = transactionresponse.get();

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

@ -11,51 +11,71 @@ import org.springframework.stereotype.Repository;
import com.gcc.communityHall.paymentService.entity.TransactionResponse;
@Repository
public interface TransactionResponseRepository extends JpaRepository<TransactionResponse, Integer> {
Optional<TransactionResponse> findByBookingId(int bookingId);
List<TransactionResponse> findByuserId(String userId);
Optional<TransactionResponse> findByTxansactionId(String txansactionId);
@Repository
public interface TransactionResponseRepository extends JpaRepository<TransactionResponse,Integer>{
Optional<TransactionResponse> findByBookingId(int bookingId);
List<TransactionResponse> findByuserId(String userId);
Optional<TransactionResponse> findByTxansactionId(String txansactionId );
Optional<TransactionResponse> findByTxansactionIdAndStatusCode(String txansactionId, String statusCode);
Optional<TransactionResponse> findByTxansactionIdAndStatusCode(String txansactionId,String statusCode );
Optional<TransactionResponse> findByBookingIdAndStatusCode(int bookingId, String statusCode);
Optional<TransactionResponse> findByBookingIdAndTxansactionIdAndStatusCode(int bookingId,String txansactionId, String statusCode);
Optional<TransactionResponse> findByBookingIdAndStatusCode(int bookingId, String statusCode);
Optional<TransactionResponse> findByBookingIdAndTxansactionIdAndStatusCode(int bookingId, String txansactionId,
String statusCode);
@Query(value = "SELECT tr.booking_id, tr.hall_id, tr.amount, tr.status_code, tr.txansaction_id, tr.user_id " +
// ", p.payment_status " +
// ", p.payment_status " +
"FROM transaction_response tr " +
"JOIN hall_details hd ON tr.hall_id = hd.hall_id " +
// "LEFT JOIN payments p ON tr.booking_id = p.booking_details_booking_id " +
// "LEFT JOIN payments p ON tr.booking_id = p.booking_details_booking_id " +
"LEFT JOIN booking_details bd ON tr.booking_id = bd.booking_id " +
"WHERE DATE(STR_TO_DATE(tr.cdate, '%Y-%m-%d')) >= STR_TO_DATE(:fromDate, '%Y-%m-%d') " +
// "WHERE DATE(STR_TO_DATE(tr.cdate, '%d-%m-%Y %H:%i:%s')) >= STR_TO_DATE(:fromDate, '%Y-%m-%d') " +
// "WHERE DATE(STR_TO_DATE(tr.cdate, '%d-%m-%Y %H:%i:%s')) >=
// STR_TO_DATE(:fromDate, '%Y-%m-%d') " +
"AND DATE(STR_TO_DATE(tr.cdate, '%Y-%m-%d')) <= STR_TO_DATE(:toDate, '%Y-%m-%d') " +
"AND (:bookingId IS NULL OR tr.booking_id = :bookingId) " +
"AND (:hallId IS NULL OR tr.hall_id = :hallId)", nativeQuery = true)
List<Object[]> getTransactionResponseByBookingId(@Param("fromDate") String fromDate,
@Param("toDate") String toDate,
@Param("bookingId") Long bookingId,
@Param("hallId") Long hallId);
// @Transactional
// @Query (value = "UPDATE transaction_response SET amount = :amount, booking_id =:booking_id , date = :date, hall_id = :hall_id, response = :response, status_code = :status_code, tpsl_txn_id = :tpsl_txn_id, txansaction_id = :txansaction_id, user_id = :user_id WHERE (id = :id)",nativeQuery = true)
// void updateTransactionResponse ( @Param("id") Integer id, @Param("amount") String amount, @Param("booking_id") int booking_id ,@Param("date" ) String date,@Param("hall_id" ) int hall_id ,@Param("response")String response,@Param("status_code")String status_code,@Param("tpsl_txn_id")String tpsl_txn_id,@Param("txansaction_id")String txansaction_id,@Param("user_id")String user_id );
// TransactionResponse saveTransactionResponse(Integer id, String amount, int bookingId, String date, int hallId, String response,
// String statusCode, String tpslTxnId, String txansactionId, String userId);
// @Query(value = "INSERT INTO transaction_response ('id','amount','booking_id','date','hall_id','response','status_code','tpsl_txn_id','txansaction_id','user_id') VALUES (:id, :amount, :booking_id, :date, :hall_id, :response, :status_code, :tpsl_txn_id, :txansaction_id, :user_id)", nativeQuery = true)
// void saveTransactionResponse(@Param("id") int id, @Param("amount") String amount, @Param("booking_id") int booking_id ,@Param("date" ) String date,@Param("hall_id" ) int hall_id ,@Param("response")String response,@Param("status_code")String status_code,@Param("tpsl_txn_id")String tpsl_txn_id,@Param("txansaction_id")String txansaction_id,@Param("user_id")String user_id );
//
//@Query (value = "UPDATE transaction_response SET 'amount' = :amount, 'booking_id' =:booking_id , 'date' = :date, 'hall_id' = :hall_id, 'response' = :response, 'status_code' = :status_code, 'tpsl_txn_id' = :tpsl_txn_id, 'txansaction_id' = :txansaction_id, 'user_id' = :user_id WHERE ('id' = :id)", nativeQuery = true)
@Param("toDate") String toDate,
@Param("bookingId") Long bookingId,
@Param("hallId") Long hallId);
// @Transactional
// @Query (value = "UPDATE transaction_response SET amount = :amount, booking_id
// =:booking_id , date = :date, hall_id = :hall_id, response = :response,
// status_code = :status_code, tpsl_txn_id = :tpsl_txn_id, txansaction_id =
// :txansaction_id, user_id = :user_id WHERE (id = :id)",nativeQuery = true)
// void updateTransactionResponse ( @Param("id") Integer id, @Param("amount")
// String amount, @Param("booking_id") int booking_id ,@Param("date" ) String
// date,@Param("hall_id" ) int hall_id ,@Param("response")String
// response,@Param("status_code")String status_code,@Param("tpsl_txn_id")String
// tpsl_txn_id,@Param("txansaction_id")String
// txansaction_id,@Param("user_id")String user_id );
// TransactionResponse saveTransactionResponse(Integer id, String amount, int
// bookingId, String date, int hallId, String response,
// String statusCode, String tpslTxnId, String txansactionId, String userId);
// @Query(value = "INSERT INTO transaction_response
// ('id','amount','booking_id','date','hall_id','response','status_code','tpsl_txn_id','txansaction_id','user_id')
// VALUES (:id, :amount, :booking_id, :date, :hall_id, :response, :status_code,
// :tpsl_txn_id, :txansaction_id, :user_id)", nativeQuery = true)
// void saveTransactionResponse(@Param("id") int id, @Param("amount") String
// amount, @Param("booking_id") int booking_id ,@Param("date" ) String
// date,@Param("hall_id" ) int hall_id ,@Param("response")String
// response,@Param("status_code")String status_code,@Param("tpsl_txn_id")String
// tpsl_txn_id,@Param("txansaction_id")String
// txansaction_id,@Param("user_id")String user_id );
//
// @Query (value = "UPDATE transaction_response SET 'amount' = :amount,
// 'booking_id' =:booking_id , 'date' = :date, 'hall_id' = :hall_id, 'response'
// = :response, 'status_code' = :status_code, 'tpsl_txn_id' = :tpsl_txn_id,
// 'txansaction_id' = :txansaction_id, 'user_id' = :user_id WHERE ('id' = :id)",
// nativeQuery = true)
@Query(value = "SELECT tr.id, tr.amount, tr.booking_id, tr.hall_id, tr.response, tr.status_code, " +
"tr.tpsl_txn_id, tr.txansaction_id, tr.user_id, bd.booking_date " +
@ -64,10 +84,12 @@ public interface TransactionResponseRepository extends JpaRepository<Transaction
"WHERE tr.status_code = ? AND bd.booking_date < DATE_SUB(CURDATE(), INTERVAL 2 DAY", nativeQuery = true)
List<Map<String, Object>> getTransactionResponseByStatus(String status);
@Query(value = "SELECT tr.id, tr.amount, tr.booking_id, tr.hall_id, tr.response, tr.tpsl_txn_id, tr.txansaction_id, tr.cdate, " +
@Query(value = "SELECT tr.id, tr.amount, tr.booking_id, tr.hall_id, tr.response, tr.tpsl_txn_id, tr.txansaction_id, tr.cdate, "
+
"tr.user_id, bd.booking_date FROM transaction_response tr " +
"INNER JOIN booking_details bd ON tr.booking_id = bd.booking_id " +
"WHERE tr.status_code = 'temp' AND tr.cdate < DATE_SUB(NOW(), INTERVAL 1 HOUR);", nativeQuery = true)
List<Map<String, Object>> getTransResBycdateandStatus(String status);
boolean existsByBookingId(int bookingId);
}

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

@ -1712,4 +1712,43 @@ public interface BookingDetailsRepository extends JpaRepository<BookingDetails,
" AND bd.counter_id IS NOT NULL " +
"GROUP BY bd.counter_id, bd.hall_details_hall_id ", nativeQuery = true)
List<Object> getCounterWiseBookingList(String fromDate, String toDate);
@Query(value = "SELECT "
+ " u.user_id as userId,"
+ " u.name as UserName,"
+ " u.mobile_no as UserMobile,"
+ " u. usertype as UserType,"
+ " CONCAT("
+ " IFNULL(u.doorno,''), ', ', "
+ " IFNULL(u.street,''), ', ', "
+ " IFNULL(u.area,''), ', ', "
+ " IFNULL(u.location,''), ' - ', "
+ " IFNULL(u.pin_code,'') "
+ " ) AS UserAddress, "
+ "hd.hall_name as hallName,"
+ " CONCAT("
+ " IFNULL(hd.door_no,''), ', ', "
+ " IFNULL(hd.street,''), ', ', "
+ " IFNULL(hd.area,''), ', ', "
+ " IFNULL(hd.city,''), ' - ', "
+ " IFNULL(hd.pin_code,'') "
+ " ) AS HallAddress, "
+ " hd.hall_incharge_name as CareTakerName,"
+ " hd.hall_incharge_no as CareTakerMobile,"
+ " bd.booking_id as bookingId,"
+ " bd.booking_date as bookingDate,"
+ " bd.start_date as start_date,"
+ " bd.end_date as end_date,"
+ "bd.deposit_amount as depositAmount,"
+ "bd.gst as gst,"
+ "bd.hall_amount as hallAmount,"
+ " bd.amount_received as totalAmount "
+ "FROM booking_details bd "
+ "INNER JOIN hall_request_details hrd "
+ "ON hrd.booking_id = bd.booking_id "
+ "LEFT JOIN hall_details hd ON hd.hall_id=bd.hall_details_hall_id "
+ "LEFT JOIN users u ON u.user_id=bd.users_user_id "
+ "WHERE bd.booking_id = :bookingId "
+ "AND hrd.booking_status = 'APPROVED'", nativeQuery = true)
List<Map<String, Object>> findApprovedBookingWithHallRequest(@Param("bookingId") int bookingId);
}

39
src/main/java/com/gcc/communityHall/repository/HallRequestDetailsRepository.java

@ -0,0 +1,39 @@
package com.gcc.communityHall.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
import org.springframework.data.jpa.repository.Query;
import com.gcc.communityHall.entity.HallRequestDetails;
@Repository
public interface HallRequestDetailsRepository extends JpaRepository<HallRequestDetails, Integer> {
@Query(value =" SELECT r.*, b.*, h.*, u.* "+
" FROM hall_request_details r "+
" JOIN booking_details b ON r.booking_id = b.booking_id "+
" JOIN hall_details h ON b.hall_details_hall_id = h.hall_id "+
" JOIN users u ON b.users_user_id = u.user_id "+
" WHERE b.booking_status = 'PENDING'", nativeQuery = true)
List<HallRequestDetails> findPendingRequests();
@Query("""
SELECT hrd FROM HallRequestDetails hrd
JOIN FETCH hrd.bookingDetails b
JOIN FETCH b.hallDetails
JOIN FETCH b.users
WHERE b.bookingStatus IN ('APPROVED', 'WAITING_FOR_NOC')
""")
List<HallRequestDetails> findApprovedRequests();
@Query("""
SELECT hrd FROM HallRequestDetails hrd
JOIN FETCH hrd.bookingDetails b
JOIN FETCH b.hallDetails
JOIN FETCH b.users
WHERE b.bookingStatus = 'REJECTED'
""")
List<HallRequestDetails> findRejectedRequests();
}

23
src/main/java/com/gcc/communityHall/repository/PaymentsRepository.java

@ -1,6 +1,5 @@
package com.gcc.communityHall.repository;
import com.gcc.communityHall.entity.Payments;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
@ -12,17 +11,21 @@ import java.util.Optional;
@Repository
public interface PaymentsRepository extends JpaRepository<Payments,Integer> {
public interface PaymentsRepository extends JpaRepository<Payments, Integer> {
@Query(value = "SELECT * FROM payments WHERE payment_status in ('paid') ",nativeQuery = true)
@Query(value = "SELECT * FROM payments WHERE payment_status in ('paid') ", nativeQuery = true)
List<Payments> getPaymentlist();
@Query(value="SELECT p.* "
+ "FROM payments p "
+ "JOIN booking_details b ON p.booking_details_booking_id = b.booking_id "
+ "JOIN hall_details h ON b.hall_details_hall_id = h.hall_id "
+ "WHERE h.zone = :zone", nativeQuery = true)
@Query(value = "SELECT p.* "
+ "FROM payments p "
+ "JOIN booking_details b ON p.booking_details_booking_id = b.booking_id "
+ "JOIN hall_details h ON b.hall_details_hall_id = h.hall_id "
+ "WHERE h.zone = :zone", nativeQuery = true)
List<Payments> getPaymentListByzone(@Param("zone") String zone);
//List<Payments> findAllWithBookingDetailsAndUsers();
@Query(value = "select * from payments where booking_details_booking_id=?",nativeQuery = true)
// List<Payments> findAllWithBookingDetailsAndUsers();
@Query(value = "select * from payments where booking_details_booking_id=?", nativeQuery = true)
Payments findByBookingId(int bookingId);
boolean existsByBookingDetails_BookingId(int bookingId);
}

5
src/main/java/com/gcc/communityHall/repository/ReasonMasterRepository.java

@ -9,7 +9,10 @@ import org.springframework.stereotype.Repository;
import com.gcc.communityHall.entity.ReasonMaster;
@Repository
public interface ReasonMasterRepository extends JpaRepository<ReasonMaster,Integer> {
public interface ReasonMasterRepository extends JpaRepository<ReasonMaster, Integer> {
ReasonMaster findByReason(String reason);
@Query(value = "select * from reason_master where is_active =1 and is_delete=0 ", nativeQuery = true)
List<ReasonMaster> getAllReasonsWithStatus();
}

268
src/main/java/com/gcc/communityHall/service/BookingService.java

@ -1,6 +1,5 @@
package com.gcc.communityHall.service;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;
@ -16,213 +15,254 @@ import com.gcc.communityHall.entity.BookingDetails.BookingStatus;
import com.gcc.communityHall.entity.BookingDetails.RefundStatus;
import com.gcc.communityHall.entity.EbDetails;
import com.gcc.communityHall.entity.GccBlockingDate;
import com.gcc.communityHall.entity.HallRequestDetails;
public interface BookingService {
BookingDetails getBookingsById(int BookingId);
//ak
BookingDetails getBookingByRefId(String refId);
//ak
void migrateOldBookingsToRefId();
BookingDetails getBookingsById(int BookingId);
// ak
BookingDetails getBookingByRefId(String refId);
// ak
void migrateOldBookingsToRefId();
BookingDetails updateBookingDetails(BookingDetails bd);
public String confirmTheDateAndSlot(String fromDate, String toDate, int days, int fromStartingSlot,
int fromEndingSlot, int toStartingSlot, int toEndingSlot, int bookingId, int userId);
public Map<String, Object> saveBookingDetails(Map<String, Object> formData);
public BookingDetails updateBookingStatustoGCCBlocked(BookingDetails bookingDetails);
public BookingDetails updateBookingStatus(int bookingId, BookingDetails.BookingStatus status, String comments);
public BookingDetails updateBookingStatusById(int bookingId, BookingDetails.BookingStatus status, String comments);
BookingDetails updateBookingDetails(BookingDetails bd);
public EbDetails updateEbDetails(int bookingId, double startUnit, double endUnit, char status);
public String confirmTheDateAndSlot(String fromDate, String toDate, int days, int fromStartingSlot, int fromEndingSlot, int toStartingSlot, int toEndingSlot, int bookingId, int userId);
// typeOfCancel depends { }
String cancelBooking(int bookingId, BookingDetails.BookingStatus currentStatus, String comments);
public Map<String, Object> saveBookingDetails(Map<String, Object> formData);
public String confirmBooking(int bookingId);
public BookingDetails updateBookingStatustoGCCBlocked(BookingDetails bookingDetails);
public BookingDetails getBookingDetailsWithSettlement(int settlementId);
public BookingDetails updateBookingStatus(int bookingId, BookingDetails.BookingStatus status, String comments);
// sreeja
List<BookingDetails> getPresentsEventsByUserId(Integer hallId);
public BookingDetails updateBookingStatusById(int bookingId, BookingDetails.BookingStatus status, String comments);
List<BookingDetails> getPastsEventsByUserId(Integer hallId);
public EbDetails updateEbDetails(int bookingId, double startUnit, double endUnit, char status);
List<BookingDetails> getFuturesEventsByUserId(Integer hallId);
//typeOfCancel depends { }
String cancelBooking(int bookingId, BookingDetails.BookingStatus currentStatus, String comments);
List<BookingDetails> getSettlementList(Integer hallId);
public String confirmBooking(int bookingId);
public List<BookingDetails> getFilteredBookings(LocalDate fromDate, LocalDate toDate, List<Long> hallIds);
public BookingDetails getBookingDetailsWithSettlement(int settlementId);
public List<BookingCalendar> getPastData(int hall_id);
public String processEbDetailsAndDamage(
int bookingId, int ebId,
double startingReading, double endingReading,
float usedUnit, double ebAmount,
String assetNames[], String comments[], int quantities[], Double assetAmounts[], MultipartFile assetImages[]);
//sreeja
List<BookingDetails> getPresentsEventsByUserId(Integer hallId);
public int checkUserBookinglimitation(int userId);
List<BookingDetails> getPastsEventsByUserId(Integer hallId);
List<BookingDetails> getAllBookingsByUserId(Integer userId);
List<BookingDetails> getFuturesEventsByUserId(Integer hallId);
List<Map<String, Object>> getAllBookingEventsByUserId(Integer userId);
List<BookingDetails> getSettlementList(Integer hallId);
// List<BookingDetails> getAllBookingDetailsWithStatus(String fromDate, String
// toDate, String bookingStatus);
public List<BookingDetails> getFilteredBookings(LocalDate fromDate, LocalDate toDate, List<Long> hallIds);
// List<Object[]> getAllPaymentsDetails( String fromDate, String toDate);
public List<BookingCalendar> getPastData(int hall_id);
List<Object[]> getBookingUserDetailsReport(String fromDate, String toDate);
public String processEbDetailsAndDamage(
int bookingId, int ebId,
double startingReading, double endingReading,
float usedUnit, double ebAmount,
String assetNames[], String comments[], int quantities[], Double assetAmounts[], MultipartFile assetImages[]);
List<Object[]> getBookingHallDetailsReport(String fromDate, String toDate);
public int checkUserBookinglimitation(int userId);
List<GccBlockingDate> getBlockedEvents(LocalDate fromDate, LocalDate toDate, List<Long> hallIds);
List<BookingDetails> getAllBookingsByUserId(Integer userId);
List<Map<String, Object>> getOfflineBookings();
List<Map<String, Object>> getAllBookingEventsByUserId(Integer userId);
List<BookingCalendar> getBookedslots(LocalDate fromDate, LocalDate endDate, List<Long> hallIdList);
BookingDetails updateCancelledBookingStatus(int bookingId, BookingStatus status, String comments);
//List<BookingDetails> getAllBookingDetailsWithStatus(String fromDate, String toDate, String bookingStatus);
BookingDetails updateRefundStatus(int bookingId, RefundStatus status);
//List<Object[]> getAllPaymentsDetails( String fromDate, String toDate);
// officer service
List<BookingDetails> getAllBookingDetailsByZone(String fromDate, String toDate, String zone);
List<Object[]> getBookingUserDetailsReport(String fromDate, String toDate);
List<BookingDetails> getAllBookingDetailsByZoneWithStatus(String fromDate, String toDate, String zone,
String bookingStatus);
List<Object[]> getBookingHallDetailsReport(String fromDate, String toDate);
List<Object[]> getAllPaymentsDetailsByZone(String fromDate, String toDate, String zone);
List<GccBlockingDate> getBlockedEvents(LocalDate fromDate, LocalDate toDate, List<Long> hallIds);
List<Object[]> getBookingHallDetailsReportByZone(String fromDate, String toDate, String zone);
List<Map<String, Object>> getOfflineBookings();
Optional<String> updateBookingDatesAndCalendar(int bookingId, String startDate, String endDate);
List<BookingCalendar> getBookedslots(LocalDate fromDate, LocalDate endDate, List<Long> hallIdList);
List<Object[]> getBookingHallDetailsReportByZone1(String fromDate, String toDate, String zone, Integer hallId);
BookingDetails updateCancelledBookingStatus(int bookingId, BookingStatus status, String comments);
List<Object> getGccBlockingEvents(String hallId);
BookingDetails updateRefundStatus(int bookingId, RefundStatus status);
int getBlockedHallCount(String blockingReason, Date startDate, Date endDate);
//officer service
List<BookingDetails> getAllBookingDetailsByZone(String fromDate, String toDate, String zone);
@Transactional
void cancelAllBookings(String fromDate, String toDate, List<Long> hallIdsList,
String reasonforblocking, List<String> selectedBookings, String updatedBy, String[] descriptions,
MultipartFile[] documents);
List<BookingDetails> getAllBookingDetailsByZoneWithStatus(String fromDate, String toDate, String zone, String bookingStatus);
List<BookingDetails> findBookingDetailsByBookingId(Long bookingId);
List<Object[]> getAllPaymentsDetailsByZone(String fromDate, String toDate, String zone);
// admin dashboard
Map<String, Map<String, Integer>> getBookingStatistics(LocalDate fromDate, LocalDate toDate, String zone,
String division, Integer hallid, String userType);
List<Object[]> getBookingHallDetailsReportByZone(String fromDate, String toDate, String zone);
public List<Map<String, Object>> getBookingDetailsByHallId(int hallId);
Optional<String> updateBookingDatesAndCalendar(int bookingId, String startDate, String endDate);
// officer dashboard
Map<String, Map<String, Integer>> getOfficerDashboard(LocalDate fromDate, LocalDate toDate, String zone,
String division, Integer hallid, String userType);
List<Object[]> getBookingHallDetailsReportByZone1(String fromDate, String toDate, String zone, Integer hallId);
List<Map<String, Object>> getHallDetailsForOfficer(Integer hallIid);
// List<Object[]> getAllPaymentsDetails(String fromDate, String toDate, String
// paymentStatus);
// admin reports
List<Object> getGccBlockingEvents(String hallId);
List<Object[]> getBookingDetailsByBookingDate(String fromDate, String toDate, String zone, String division,
Integer hallid);
int getBlockedHallCount(String blockingReason, Date startDate, Date endDate);
List<Object[]> getBookingDetailsByEventDate(String fromDate, String toDate, String zone, String division,
Integer hallid);
@Transactional
void cancelAllBookings(String fromDate, String toDate, List<Long> hallIdsList,
String reasonforblocking, List<String> selectedBookings, String updatedBy, String[] descriptions, MultipartFile[] documents);
List<Object[]> getBookingDetailsByBookingDateWithStatus(String fromDate, String toDate, String bookingStatus,
String zone, String division, Integer hallid);
List<BookingDetails> findBookingDetailsByBookingId(Long bookingId);
List<Object[]> getBookingDetailsByEventDateWithStatus(String fromDate, String toDate, String bookingStatus,
String zone, String division, Integer hallid);
//admin dashboard
Map<String, Map<String, Integer>> getBookingStatistics(LocalDate fromDate, LocalDate toDate, String zone, String division, Integer hallid, String userType);
List<Object[]> getAllPaymentsDetails(String fromDate, String toDate, String paymentStatus, String zone,
String division, Integer hallid);
public List<Map<String, Object>> getBookingDetailsByHallId(int hallId);
List<Object[]> getBookingHallDetailsReportByBookingDate(String fromDate, String toDate, String zone, String division,
Integer hallid);
//officer dashboard
Map<String, Map<String, Integer>> getOfficerDashboard(LocalDate fromDate, LocalDate toDate, String zone, String division, Integer hallid, String userType);
List<Object[]> getBookingHallDetailsReportByEventDate(String fromDate, String toDate, String zone, String division,
Integer hallid);
List<Map<String, Object>> getHallDetailsForOfficer(Integer hallIid);
//List<Object[]> getAllPaymentsDetails(String fromDate, String toDate, String paymentStatus);
//admin reports
List<BookingDetails> getAllBookingsettlementDetailsByBookingDate(String fromDate, String toDate);
List<Object[]> getBookingDetailsByBookingDate(String fromDate, String toDate, String zone, String division, Integer hallid);
List<BookingDetails> getAllBookingsettlementDetailsByBookingDateWithStatus(String fromDate, String toDate,
String refundStatus);
List<Object[]> getBookingDetailsByEventDate(String fromDate, String toDate, String zone, String division, Integer hallid);
List<BookingDetails> getAllBookingsettlementDetailsByEventDate(String fromDate, String toDate);
List<Object[]> getBookingDetailsByBookingDateWithStatus(String fromDate, String toDate, String bookingStatus, String zone, String division, Integer hallid);
List<BookingDetails> getAllBookingsettlementDetailsByEventDateWithStatus(String fromDate, String toDate,
String refundStatus);
List<Object[]> getBookingDetailsByEventDateWithStatus(String fromDate, String toDate, String bookingStatus, String zone, String division, Integer hallid);
List<BookingDetails> getAllBookingDetailsBookingDateByZone(String fromDate, String toDate, String zone);
List<Object[]> getAllPaymentsDetails(String fromDate, String toDate, String paymentStatus, String zone, String division, Integer hallid);
List<BookingDetails> getAllBookingDetailsEventDateByZone(String fromDate, String toDate, String zone);
List<Object[]> getBookingHallDetailsReportByBookingDate(String fromDate, String toDate, String zone, String division, Integer hallid);
List<BookingDetails> getAllBookingDetailsBookingDateByZoneWithStatus(String fromDate, String toDate, String zone,
String bookingStatus);
List<Object[]> getBookingHallDetailsReportByEventDate(String fromDate, String toDate, String zone, String division, Integer hallid);
List<BookingDetails> getAllBookingDetailsEventDateByZoneWithStatus(String fromDate, String toDate, String zone,
String bookingStatus);
List<BookingDetails> getAllBookingsettlementDetailsByBookingDate(String fromDate, String toDate);
List<BookingDetails> getAllBookingsettlementDetailsByZoneByBookingDate(String fromDate, String toDate, String zone);
List<BookingDetails> getAllBookingsettlementDetailsByBookingDateWithStatus(String fromDate, String toDate, String refundStatus);
List<BookingDetails> getAllBookingsettlementDetailsByZoneByEventDate(String fromDate, String toDate, String zone);
List<BookingDetails> getAllBookingsettlementDetailsByEventDate(String fromDate, String toDate);
List<BookingDetails> getAllBookingsettlementDetailsByZoneByBookingDateWithStatus(String fromDate, String toDate,
String zone, String refundStatus);
List<BookingDetails> getAllBookingsettlementDetailsByEventDateWithStatus(String fromDate, String toDate, String refundStatus);
List<BookingDetails> getAllBookingsettlementDetailsByZoneByEventDateWithStatus(String fromDate, String toDate,
String zone, String refundStatus);
List<BookingDetails> getAllBookingDetailsBookingDateByZone(String fromDate, String toDate, String zone);
List<Object[]> getBookingHallDetailsReportByZoneByBookingDate(String fromDate, String toDate, String zone);
List<BookingDetails> getAllBookingDetailsEventDateByZone(String fromDate, String toDate, String zone);
List<Object[]> getBookingHallDetailsReportByZoneByEventDate(String fromDate, String toDate, String zone);
List<BookingDetails> getAllBookingDetailsBookingDateByZoneWithStatus(String fromDate, String toDate, String zone, String bookingStatus);
List<Object[]> getBookingHallDetailsReportByZoneByBookingDateHallname(String fromDate, String toDate, String zone,
Integer hallId);
List<BookingDetails> getAllBookingDetailsEventDateByZoneWithStatus(String fromDate, String toDate, String zone, String bookingStatus);
List<Object[]> getBookingHallDetailsReportByZoneByEventDateHallname(String fromDate, String toDate, String zone,
Integer hallId);
List<BookingDetails> getAllBookingsettlementDetailsByZoneByBookingDate(String fromDate, String toDate, String zone);
BookingDetails saveebdetails(int bookingId, double startingReading, MultipartFile startingReadingimage);
List<BookingDetails> getAllBookingsettlementDetailsByZoneByEventDate(String fromDate, String toDate, String zone);
String confirmStateBooking(int bookingId);
List<BookingDetails> getAllBookingsettlementDetailsByZoneByBookingDateWithStatus(String fromDate, String toDate, String zone, String refundStatus);
String uploadNOCFile(MultipartFile file, int bookingId);
List<BookingDetails> getAllBookingsettlementDetailsByZoneByEventDateWithStatus(String fromDate, String toDate, String zone, String refundStatus);
// gccapps
List<BookingDetails> getApprovedBookingDetails();
List<Object[]> getBookingHallDetailsReportByZoneByBookingDate(String fromDate, String toDate, String zone);
List<BookingDetails> getRejectedBookingDetails();
List<Object[]> getBookingHallDetailsReportByZoneByEventDate(String fromDate, String toDate, String zone);
List<Object[]> getAllPaymentsDetails(String fromDate, String toDate);
List<Object[]> getBookingHallDetailsReportByZoneByBookingDateHallname(String fromDate, String toDate, String zone, Integer hallId);
List<BookingDetails> getPastsEvents();
List<Object[]> getBookingHallDetailsReportByZoneByEventDateHallname(String fromDate, String toDate, String zone, Integer hallId);
List<BookingDetails> getPresentsEvents();
BookingDetails saveebdetails(int bookingId, double startingReading, MultipartFile startingReadingimage);
List<BookingDetails> getFuturesEvents();
String confirmStateBooking(int bookingId);
List<BookingDetails> getSettlementApprovedList();
String uploadNOCFile(MultipartFile file, int bookingId);
List<Map<String, Object>> getHallDetails(Integer hall_id);
//gccapps
List<BookingDetails> getApprovedBookingDetails();
List<BookingDetails> getWaitingforNOCapproval();
List<BookingDetails> getRejectedBookingDetails();
List<Object[]> getAllExtraPaymentsDetails(String fromDate, String toDate, String paymentStatus, String zone,
String division, Integer hallid);
List<Object[]> getAllPaymentsDetails(String fromDate, String toDate);
// developer
List<Object[]> getTransactionresponse(String fromDate, String toDate, Long bookingId, Long hallId);
List<BookingDetails> getPastsEvents();
List<Object[]> getRefundResponse(String fromDate, String toDate, Long bookingId);
List<BookingDetails> getPresentsEvents();
List<Object[]> getBookingCalendarDetails(String fromDate, String toDate, Long bookingId, String hallName);
List<BookingDetails> getFuturesEvents();
List<BookingDetails> getBookingsByDateAndHall(String bookingDate, Long hallId);
List<BookingDetails> getSettlementApprovedList();
BookingDetails updateRefundStatusScheduler(int bookingId, RefundStatus status);
List<Map<String, Object>> getHallDetails(Integer hall_id);
List<Object[]> getCounterWiseBookingCount(String fromDate, String toDate);
List<BookingDetails> getWaitingforNOCapproval();
List<Object[]> getHallWiseBookingDetails(String fromDate, String toDate, String CounterId);
List<Object[]> getAllExtraPaymentsDetails(String fromDate, String toDate, String paymentStatus, String zone, String division, Integer hallid);
List<Object[]> getBookingDetailsForAllHalls(String fromDate, String toDate, String CounterId, Integer hallid);
//developer
List<Object[]> getTransactionresponse(String fromDate, String toDate, Long bookingId, Long hallId);
List<Object[]> getCounterWiseBookingDetails(String fromDate, String toDate);
List<Object[]> getRefundResponse(String fromDate, String toDate, Long bookingId);
List<Object> getZoneWiseBookingList(String fromDate, String toDate);
List<Object[]> getBookingCalendarDetails(String fromDate, String toDate, Long bookingId, String hallName);
List<Object> getAllHallWiseBookingList(String fromDate, String toDate);
List<BookingDetails> getBookingsByDateAndHall(String bookingDate, Long hallId);
List<Object> getAllCounterWiseBookingList(String fromDate, String toDate);
BookingDetails updateRefundStatusScheduler(int bookingId, RefundStatus status);
// ak
List<Object[]> getSettlementInitiatedReport(String fromDate, String toDate);
List<Object[]> getCounterWiseBookingCount(String fromDate, String toDate);
public String saveHallRequestDetails(String fromDate, String toDate, int startingSlot,
int endingSlot, String relationship, String reason, int hallId, int userId,
String orgType, String eventDesc, String offAddress, MultipartFile bonafide);
List<Object[]> getHallWiseBookingDetails(String fromDate, String toDate, String CounterId);
List<HallRequestDetails> getPendingGovtRequests();
List<Object[]> getBookingDetailsForAllHalls(String fromDate, String toDate, String CounterId, Integer hallid);
List<HallRequestDetails> getApprovedGovtRequests();
List<Object[]> getCounterWiseBookingDetails(String fromDate, String toDate);
List<HallRequestDetails> getRejectedGovtRequests();
List<Object> getZoneWiseBookingList(String fromDate, String toDate);
void updateGovtRequest(int reqId, String action, double discountPercentage, boolean nocRequired);
List<Object> getAllHallWiseBookingList(String fromDate, String toDate);
List<Map<String, Object>> getvphcollectionpending(int bookingId);
List<Object> getAllCounterWiseBookingList(String fromDate, String toDate);
//ak
List<Object[]> getSettlementInitiatedReport(String fromDate, String toDate);
boolean isPaymentAlreadyDoneOrInitiated(int bookingId);
}

374
src/main/java/com/gcc/communityHall/service/Impl/BookingServiceImpl.java

@ -3,6 +3,7 @@ package com.gcc.communityHall.service.Impl;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
@ -46,6 +47,7 @@ import com.gcc.communityHall.entity.GccBlockingHistory;
import com.gcc.communityHall.entity.GccblockingDocuments;
import com.gcc.communityHall.entity.HallDetails;
import com.gcc.communityHall.entity.HallDetailsConcession;
import com.gcc.communityHall.entity.HallRequestDetails;
import com.gcc.communityHall.entity.ReasonDocumentMaster;
import com.gcc.communityHall.entity.ReasonMaster;
import com.gcc.communityHall.entity.Settlement;
@ -72,6 +74,8 @@ import com.gcc.communityHall.repository.ReasonMasterRepository;
import com.gcc.communityHall.repository.SettlementHistoryRepository;
import com.gcc.communityHall.repository.SettlementRepository;
import com.gcc.communityHall.repository.UsersRepository;
import com.gcc.communityHall.repository.HallRequestDetailsRepository;
import com.gcc.communityHall.repository.PaymentsRepository;
import com.gcc.communityHall.service.ApplicationLogService;
import com.gcc.communityHall.service.BookingService;
import com.gcc.communityHall.service.DiscountRangeService;
@ -163,6 +167,12 @@ public class BookingServiceImpl implements BookingService {
@Autowired
private TransRefundResRepository transRefundResRepository;
@Autowired
private HallRequestDetailsRepository hallRequestDetailsRepository;
@Autowired
private PaymentsRepository paymentsRepository;
@Value("${file.upload.directory}")
private String uploadDirectory;
@ -242,6 +252,16 @@ public class BookingServiceImpl implements BookingService {
@Override
public BookingDetails updateBookingStatus(int bookingId, BookingDetails.BookingStatus status, String comments) {
Optional<BookingDetails> booking = bookingDetailsRepository.findById(bookingId);
String apikey = "5c995535-6244-11f0-98fc-02c8a5e042bd";
String from = "919445061913";
String hallName, userName, endDate;
// String[] numbers = { "9123565217", "9789091845", "9894935693", "8667881667"
// }; // for testing purpose
String[] numbers = { "9123565217", "9789091845", "9894935693",
"9444173345", "9994697909", "9176617754", "9445190998", "9381013498",
"9789977111" };
if (booking.isPresent()) {
BookingDetails book = booking.get();
/*
@ -260,6 +280,39 @@ public class BookingServiceImpl implements BookingService {
book.setBookingStatus(status);
book.setComments(comments);
BookingDetails bookings = bookingDetailsRepository.save(book);
if ("APPROVED".equals(status)) {
for (String mobNo : numbers) {
hallName = bookings.getHallDetails().getHallName();
userName = bookings.getUsers().getName();
// Format endDate from yyyy-MM-dd to dd-MM-yyyy
String rawEndDate = bookings.getEndDate();
try {
LocalDate date = LocalDate.parse(rawEndDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
endDate = date.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"));
} catch (Exception e) {
endDate = rawEndDate; // Fallback to original if parsing fails
}
String placeholders = "";
try {
placeholders = URLEncoder.encode(userName + "|~|" + hallName + "|~|" + endDate, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String whatsappMsg = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?apikey=" + apikey + "&from="
+ from
+ "&to=91" + mobNo + ""
+ "&type=template&templateid=2815237&placeholders=" + placeholders + "";
System.out.println(whatsappMsg + ":" + mobNo);
whatsappMsgServiceImpl.sendMsg(whatsappMsg);
}
}
return bookings;
}
return null;
@ -280,7 +333,7 @@ public class BookingServiceImpl implements BookingService {
Optional<BookingDetails> bookingDet = bookingDetailsRepository.findById(bookingId);
if (!bookingDet.isPresent()) {
// Handle invalid booking ID
// Handle invalid booking I D
return "Invalid booking ID";
}
bookingDetails = bookingDet.get();
@ -471,13 +524,21 @@ public class BookingServiceImpl implements BookingService {
public String processBookingStatusAndSendMessages(BookingDetails bookingDetails, String hallName, String userName,
LocalDate endDate) {
try {
String apikey = "5c995535-6244-11f0-98fc-02c8a5e042bd";
String from = "919445061913";
String reason = bookingDetails.getReason();
ReasonMaster reasonDetails = reasonMasterRepository.findByReason(reason);
String reasonCode = (reasonDetails != null && reasonDetails.getReasoncode() != null)
? reasonDetails.getReasoncode()
: "";
String[] numbers = { "9123565217", "9789091845", "9894935693", "9444173345", "9840562783", "9842042722", "9176617754" };
// String[] numbers = { "9123565217", "9789091845", "9894935693", "8667881667"
// }; // for testing purpose
String[] numbers = { "9123565217", "9789091845", "9894935693",
"9444173345", "9994697909", "9176617754", "9445190998", "9381013498",
"9789977111" };
String bookingconfirmationmsg, urlString, whatsupmsg, bookingmsg;
@ -507,16 +568,25 @@ public class BookingServiceImpl implements BookingService {
// String endDateStr = endDate+"-%20Test%20message%20please%20ignore";
String msg = "A%20new%20"+ encodedHN + "%20booking%20has%20been%20successfully%20made%20by%20"+ userName +"%20for%20" + endDate+ ".";
String msg = "A%20new%20" + encodedHN + "%20booking%20has%20been%20successfully%20made%20by%20"
+ userName + "%20for%20" + endDate + ".";
String encodedFooter = URLEncoder.encode("- GCC IT Cell", StandardCharsets.UTF_8);
bookingmsg = "https://mediaapi.smsgupshup.com/GatewayAPI/rest?userid=2000233507&password=h2YjFNcJ" +
"&send_to=" + mobNo + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg="+msg+"&isTemplate=true&footer="+encodedFooter+"";
"&send_to=" + mobNo + "&v=1.1&format=json&msg_type=TEXT&method=SENDMESSAGE&msg=" + msg
+ "&isTemplate=true&footer=" + encodedFooter + "";
System.out.println(bookingmsg + ":" + mobNo);
String placeholders = URLEncoder.encode(hallName + "|~|" + userName + "|~|" + endDate, "UTF-8");
String whatsappMsg = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?apikey=" + apikey + "&from="
+ from + "&to=91" + mobNo + ""
+ "&type=template&templateid=2815236&placeholders=" + placeholders + "";
System.out.println(bookingmsg+":"+mobNo);
System.out.println(whatsappMsg + ":" + mobNo);
whatsappMsgServiceImpl.sendMsg(bookingmsg);
whatsappMsgServiceImpl.sendMsg(whatsappMsg);
}
// whatsappMsgServiceImpl.sendSMS(urlString);
return "Waiting For NOC Documents";
@ -817,10 +887,12 @@ public class BookingServiceImpl implements BookingService {
}
@Override
@Transactional
public Map<String, Object> saveBookingDetails(Map<String, Object> formData) {
Map<String, Object> hs = new HashMap<>();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
BookingDetails bookingDetails = null;
List<BookingDocuments> uploadedDocs = new ArrayList<>();
Integer userId = userSession.getUserId();
String counterId = userSession.getCounter();
@ -926,7 +998,7 @@ public class BookingServiceImpl implements BookingService {
hs.put("reasoncode", reasoncode);
HallDetailsConcession governmentevents = hallDetailsConcessionRepo
.findbyhallId(hallDetails.getHallId());
if (reasoncode.equals("SGE")) {
if (reasoncode.equals("CGE")) {
discountAmount = (governmentevents.getFulldayhallamount() * hallDetails.getSGEdiscount()) / 100;
// hallAmount = governmentevents.getFulldayhallamount();
hallAmount = hallAmount - discountAmount;
@ -946,7 +1018,7 @@ public class BookingServiceImpl implements BookingService {
bookingDetails.setAmountReceived(truncatedTotalAmount);
hs.put("additionalcharges", additionalcharges);
hs.put("totalAmount", truncatedTotalAmount);
} else if (reasoncode.equals("CGE")) {
} else if (reasoncode.equals("SGE")) {
discountAmount = (hallDetails.getFullDayRent() * hallDetails.getCGEdiscount()) / 100;
// hallAmount = hallDetails.getFullDayRent();
hallAmount = governmentevents.getFulldayhallamount();
@ -1048,30 +1120,48 @@ public class BookingServiceImpl implements BookingService {
if (reasonMaster != null) {
List<ReasonDocumentMaster> reasonDocMaster = reasonMaster.getReasonDocumentMasterList();
List<BookingDocuments> uploadedDocs = new ArrayList<>();
for (ReasonDocumentMaster rm : reasonDocMaster) {
BookingDocuments bd = new BookingDocuments();
bd.setBookingDetails(bookingDetails);
boolean hasContent = false;
if (rm.isAddTextField()) {
bd.setName(formData.get(rm.getFieldName()).toString());
bd.setBooking_label(rm.getFieldName());
Object textFieldValue = formData.get(rm.getFieldName());
if (textFieldValue != null && !textFieldValue.toString().isEmpty()) {
bd.setName(textFieldValue.toString());
bd.setBooking_label(rm.getFieldName());
hasContent = true;
}
}
if (rm.isAddDocumentField()) {
MultipartFile file = (MultipartFile) formData.get(rm.getDocFieldName());
bd.setBookingDocUrl(serverPath + "images/" + reasonMaster.getReason() + "/"
+ bookingDetails.getBookingId() + "_" + file.getOriginalFilename());
String filePath = uploadDirectory + "/" + reasonMaster.getReason() + "/"
+ bookingDetails.getBookingId() + "_" + file.getOriginalFilename();
bd.setDocumentName(file.getOriginalFilename());
bd.setDocumentType(file.getContentType());
if (file != null && !file.isEmpty()) {
bd.setBookingDocUrl(serverPath + "images/" + reasonMaster.getReason() + "/"
+ bookingDetails.getBookingId() + "_" + file.getOriginalFilename());
String filePath = uploadDirectory + "/" + reasonMaster.getReason() + "/"
+ bookingDetails.getBookingId() + "_" + file.getOriginalFilename();
bd.setDocumentName(file.getOriginalFilename());
bd.setDocumentType(file.getContentType());
// Ensure directory exists
File dir = new File(uploadDirectory + "/" + reasonMaster.getReason());
if (!dir.exists()) {
dir.mkdirs();
}
try (FileOutputStream fos = new FileOutputStream(filePath)) {
byte[] bytes = file.getBytes();
fos.write(bytes);
} catch (Exception e) {
throw new RuntimeException(e);
try (FileOutputStream fos = new FileOutputStream(filePath)) {
byte[] bytes = file.getBytes();
fos.write(bytes);
hasContent = true;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
if (hasContent) {
bookingDocumentsRepository.save(bd);
uploadedDocs.add(bd);
}
@ -1080,6 +1170,12 @@ public class BookingServiceImpl implements BookingService {
}
}
if (bookingDetails != null) {
String refId = getBookingRefIdByBookingId(bookingDetails.getBookingId());
hs.put("bookingRefId", refId);
}
hs.put("uploadedDocs", uploadedDocs);
return hs;
}
@ -3009,4 +3105,238 @@ public class BookingServiceImpl implements BookingService {
return bookingDetailsRepository.getCounterWiseBookingList(fromDate, toDate);
}
@Override
public String saveHallRequestDetails(String fromDate, String toDate, int startingSlot, int endingSlot,
String relationship, String reason, int hallId, int userId,
String orgType, String eventDesc, String offAddress, MultipartFile bonafide) {
String exMsg = "Slot occupied";
HallDetails hallDetails = hallDetailService.getHallById(hallId);
Users user = userService.getUserById(userId);
HallRequestDetails hallRequestDetails = new HallRequestDetails();
hallRequestDetails.setStartDate(fromDate);
hallRequestDetails.setEndDate(toDate);
hallRequestDetails.setStartingSlot(startingSlot);
hallRequestDetails.setEndingSlot(endingSlot);
hallRequestDetails.setReason(reason);
hallRequestDetails.setHallId(hallId);
hallRequestDetails.setUserId(userId);
hallRequestDetails.setOrgType(orgType);
hallRequestDetails.setEventDescription(eventDesc);
hallRequestDetails.setOfficeDetails(offAddress);
if (bonafide != null && !bonafide.isEmpty()) {
hallRequestDetails.setBonafidePath(serverPath + "images/" + bonafide.getOriginalFilename());
String filePath = uploadDirectory + "/" + bonafide.getOriginalFilename();
// File saving logic is missing here in original method, but NCP is fixed.
} else {
hallRequestDetails.setBonafidePath(null);
}
hallRequestDetailsRepository.save(hallRequestDetails);
BookingDetails bookingDetails = new BookingDetails();
bookingDetails.setBookingDate(LocalDate.now());
bookingDetails.setBookingStatus(BookingStatus.PENDING);
bookingDetails.setBookingtype(BookingDetails.BookingType.ONLINE);
bookingDetails.setEndDate(toDate);
bookingDetails.setStartDate(fromDate);
bookingDetails.setStartingSlot(startingSlot);
bookingDetails.setEndingSlot(endingSlot);
bookingDetails.setReason(reason);
bookingDetails.setNoOfDays(1);
bookingDetails.setRefundStatus(RefundStatus.WAITING);
bookingDetails.setScheduleCount(0);
bookingDetails.setRelationship(relationship);
bookingDetails.setComments("Booking Slot not Confirmed.");
bookingDetails.setUsers(user);
bookingDetails.setHallDetails(hallDetails);
BookingDetails SavedBookingDetails = bookingDetailsRepository.save(bookingDetails);
int bookingId = SavedBookingDetails.getBookingId();
// BookingCalendar bookingCalendar = new BookingCalendar();
// bookingCalendar.setBookingDetails(bookingDetails);
// bookingCalendar.setBookingDate(LocalDate.parse(fromDate));
// bookingCalendar.setStartingSlot(startingSlot);
// bookingCalendar.setEndingSlot(endingSlot);
// bookingCalendar.setHallDetails(hallDetails);
// bookingCalendar.setUsers(user);
// bookingCalendarRepository.save(bookingCalendar);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate startDate = LocalDate.parse(fromDate, formatter);
LocalDate endDate = LocalDate.parse(toDate, formatter);
int i = 0;
for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) {
BookingCalendar bookingCalendar = bookingCalendarRepository.findByBdateAndHallId(date, hallId);
if (bookingCalendar != null) {
if (bookingCalendar.getIs_blocked()) {
throw new RuntimeException("GCC Blocked Date");
} else if ((date.equals(startDate) && bookingDetails.getStartingSlot() == 1
&& bookingCalendar.isMorningSlot()) ||
(date.equals(startDate) && bookingDetails.getStartingSlot() == 2
&& bookingCalendar.isEveningSlot())
||
(date.equals(endDate) && bookingDetails.getEndingSlot() == 1
&& bookingCalendar.isMorningSlot())
||
(date.equals(endDate) && bookingDetails.getEndingSlot() == 2
&& bookingCalendar.isEveningSlot())) {
// System.out.println("booking slot occupied:- 218");
throw new RuntimeException(exMsg);
} else if (bookingCalendar.isMorningSlot() && bookingCalendar.isEveningSlot()) {
// System.out.println("booking slot occupied:- 221");
throw new RuntimeException(exMsg);
} else if (!date.equals(endDate) && i != 0 && i != Math.round(bookingDetails.getNoOfDays() - 1)
&& (bookingCalendar.isMorningSlot() || bookingCalendar.isEveningSlot())) {
// System.out.println("booking slot occupied:- 227
// :-"+Math.round(bookingDetails.getNoOfDays()-1) );
throw new RuntimeException(exMsg);
} else if (date.equals(endDate) && bookingDetails.getEndingSlot() == 2
&& bookingCalendar.isMorningSlot()
&& i != 0 && i == Math.round(bookingDetails.getNoOfDays() - 1)) {
// System.out.println("booking slot occupied:- 240
// :-"+Math.round(bookingDetails.getNoOfDays()-1) );
throw new RuntimeException(exMsg);
}
} else {
String uniqueId = date.format(DateTimeFormatter.ofPattern("yyyyMMdd")) + hallId;
System.out.println("uniqueId....." + uniqueId);
bookingCalendar = new BookingCalendar();
bookingCalendar.setBdate(date);
bookingCalendar.setHallId(hallId);
bookingCalendar.setIs_booked(0);
bookingCalendar.setIs_active(true);
bookingCalendar.setUnique_id(uniqueId);
}
// Mark the appropriate slot as booked based on starting and ending slots
if (date.equals(startDate)) {
// System.out.println(i + "start :-"+bookingCalendar.toString());
if (bookingDetails.getStartingSlot() == 1) {
bookingCalendar.setMorningSlot(true);
bookingCalendar.setBookingId_1(String.valueOf(bookingId));
bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1);
if (!date.equals(endDate)) {
bookingCalendar.setEveningSlot(true);
bookingCalendar.setBookingId_2(String.valueOf(bookingId));
bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1);
} else if (startDate.equals(endDate) && bookingDetails.getStartingSlot() == 1
&& bookingDetails.getEndingSlot() == 2) {
bookingCalendar.setEveningSlot(true);
bookingCalendar.setBookingId_2(String.valueOf(bookingId));
bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1);
}
} else {
bookingCalendar.setEveningSlot(true);
bookingCalendar.setBookingId_2(String.valueOf(bookingId));
bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1);
}
} else if (date.equals(endDate)) {
if (bookingDetails.getEndingSlot() == 1) {
bookingCalendar.setMorningSlot(true);
bookingCalendar.setBookingId_1(String.valueOf(bookingId));
bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1);
} else {
bookingCalendar.setEveningSlot(true);
bookingCalendar.setBookingId_2(String.valueOf(bookingId));
bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1);
if (bookingDetails.getEndingSlot() == 2) {
bookingCalendar.setMorningSlot(true);
bookingCalendar.setBookingId_1(String.valueOf(bookingId));
bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 1);
}
}
} else {
// For dates between start and end date, mark both slots as booked
bookingCalendar.setMorningSlot(true);
bookingCalendar.setEveningSlot(true);
bookingCalendar.setBookingId_1(String.valueOf(bookingId));
bookingCalendar.setBookingId_2(String.valueOf(bookingId));
bookingCalendar.setIs_booked(bookingCalendar.getIs_booked() + 2);
}
// System.out.println(i + "end:-"+bookingCalendar.toString());
bookingCalendarRepository.save(bookingCalendar);
i++;
}
bookingDetailsRepository.save(bookingDetails);
return "success";
}
@Override
public List<HallRequestDetails> getPendingGovtRequests() {
return hallRequestDetailsRepository.findPendingRequests();
}
@Override
public List<HallRequestDetails> getApprovedGovtRequests() {
return hallRequestDetailsRepository.findApprovedRequests();
}
@Override
public List<HallRequestDetails> getRejectedGovtRequests() {
return hallRequestDetailsRepository.findRejectedRequests();
}
@Override
@Transactional
public void updateGovtRequest(int reqId, String action, double discountPercentage, boolean nocRequired) {
HallRequestDetails request = hallRequestDetailsRepository.findById(reqId)
.orElseThrow(() -> new RuntimeException("Request not found"));
BookingDetails booking = bookingDetailsRepository.findById(request.getBookingId())
.orElseThrow(() -> new RuntimeException("Booking not found"));
if ("ACCEPT".equalsIgnoreCase(action)) {
if (nocRequired) {
request.setBookingStatus("WAITING_FOR_NOC");
booking.setBookingStatus(BookingStatus.WAITING_FOR_NOC);
} else {
request.setBookingStatus("APPROVED");
booking.setBookingStatus(BookingStatus.APPROVED);
}
// Apply discount
if (discountPercentage > 0) {
float discountFactor = (float) (1 - (discountPercentage / 100));
booking.setHallAmount(booking.getHallAmount() * discountFactor);
booking.setDepositAmount(booking.getDepositAmount() * discountFactor);
booking.setGst(booking.getGst() * discountFactor);
}
} else if ("REJECT".equalsIgnoreCase(action)) {
request.setBookingStatus("REJECTED");
booking.setBookingStatus(BookingStatus.REJECTED);
}
hallRequestDetailsRepository.save(request);
bookingDetailsRepository.save(booking);
}
@Override
public List<Map<String, Object>> getvphcollectionpending(int bookingId) {
return bookingDetailsRepository.findApprovedBookingWithHallRequest(bookingId);
}
public boolean isPaymentAlreadyDoneOrInitiated(int bookingId) {
boolean existsInPayments = paymentsRepository.existsByBookingDetails_BookingId(bookingId);
boolean existsInTransaction = transactionResponseRepository.existsByBookingId(bookingId);
return existsInPayments || existsInTransaction;
}
}

63
src/main/java/com/gcc/communityHall/service/Impl/ReasonMasterImpl.java

@ -38,33 +38,33 @@ public class ReasonMasterImpl implements ReasonMasterService {
@Override
public String saveTheReason(ReasonMaster reasonMaster) {
List<ReasonDocumentMaster> reasonDocumentMasterList =reasonMaster.getReasonDocumentMasterList();
List<ReasonDocumentMaster> reasonDocumentMasterList = reasonMaster.getReasonDocumentMasterList();
reasonMaster.setReasonDocumentMasterList(null);
ReasonMaster resMaster =reasonMasterRepository.save(reasonMaster);
ReasonMaster resMaster = reasonMasterRepository.save(reasonMaster);
webConfig.addResourceHandlers(webConfig.registryHandler);
if(reasonDocumentMasterList!=null) {
if (reasonDocumentMasterList != null) {
for (ReasonDocumentMaster reasonDocMaster : reasonDocumentMasterList) {
reasonDocMaster.setReasonMaster(resMaster);
reasonDocMasterRepository.save(reasonDocMaster);
}
}
String adminname = (String) session.getAttribute("usertype");
Integer loginid = (Integer) session.getAttribute("id");
ApplicationLogs logs=new ApplicationLogs();
logs.setComments("Action by " + adminname);
logs.setLoginId(loginid);
logs.setLogType("Reasons:-"+reasonMaster.getReason());
InetAddress inetAddress;
try {
inetAddress = InetAddress.getLocalHost();
String hostname = InetAddress.getLocalHost().getHostName();
logs.setIpaddress(inetAddress.getHostAddress());
logs.setSystemName(hostname);
} catch (UnknownHostException e) {
e.printStackTrace();
}
applicationLogsRepository.save(logs);
String adminname = (String) session.getAttribute("usertype");
Integer loginid = (Integer) session.getAttribute("id");
ApplicationLogs logs = new ApplicationLogs();
logs.setComments("Action by " + adminname);
logs.setLoginId(loginid);
logs.setLogType("Reasons:-" + reasonMaster.getReason());
InetAddress inetAddress;
try {
inetAddress = InetAddress.getLocalHost();
String hostname = InetAddress.getLocalHost().getHostName();
logs.setIpaddress(inetAddress.getHostAddress());
logs.setSystemName(hostname);
} catch (UnknownHostException e) {
e.printStackTrace();
}
applicationLogsRepository.save(logs);
return "Success";
}
@ -73,17 +73,24 @@ public class ReasonMasterImpl implements ReasonMasterService {
return reasonMasterRepository.findById(reasonId).get();
}
@Override
public List<ReasonMaster> getAllReasons() {
return reasonMasterRepository.findAll();
}
@Override
public List<ReasonDocumentMaster> getReasonDocumentDetailsByReasonId(int reasonId) {
return reasonDocMasterRepository.findByReasonMasterReasonId(reasonId);
}
@Override
public List<ReasonMaster> getAllReasons() {
return reasonMasterRepository.findAll();
}
@Override
public List<ReasonDocumentMaster> getReasonDocumentDetailsByReasonId(int reasonId) {
return reasonDocMasterRepository.findByReasonMasterReasonId(reasonId);
}
@Override
@Override
public ReasonMaster getReasonByName(String reasonName) {
return reasonMasterRepository.findByReason(reasonName);
}
@Override
public List<ReasonMaster> getAllReasonsWithStatus() {
return reasonMasterRepository.getAllReasonsWithStatus();
}
}

10
src/main/java/com/gcc/communityHall/service/ReasonMasterService.java

@ -7,9 +7,15 @@ import com.gcc.communityHall.entity.ReasonMaster;
public interface ReasonMasterService {
String saveTheReason(ReasonMaster reasonMaster);
ReasonMaster getReasonById(int reasonId);
String saveTheReason(ReasonMaster reasonMaster);
ReasonMaster getReasonById(int reasonId);
List<ReasonMaster> getAllReasons();
List<ReasonDocumentMaster> getReasonDocumentDetailsByReasonId(int reasonId);
ReasonMaster getReasonByName(String reasonName);
List<ReasonMaster> getAllReasonsWithStatus();
}

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

@ -2188,7 +2188,7 @@
// $("#rentamount_td").html(response.rentAmount);
$("#actualhallAmount_td").html(response.actualhallamount);
// $("#hallAmount_td").html(response.netAmount);
$("#gst_td").html(response.gstAmount);
$("#gst_td").html(response.gst);
$("#depositAmount_td").html(response.depositAmount);
// $("#discount_td").html(response.discount + "%");
$("#totalAmount_td").html(response.totalAmount);

Loading…
Cancel
Save