diff --git a/gcc_officer_portal/src/main/java/in/gov/chennaicorporation/gccoffice/nulm/controller/NulmAPIController.java b/gcc_officer_portal/src/main/java/in/gov/chennaicorporation/gccoffice/nulm/controller/NulmAPIController.java index 0be74a99..cdd8df4c 100644 --- a/gcc_officer_portal/src/main/java/in/gov/chennaicorporation/gccoffice/nulm/controller/NulmAPIController.java +++ b/gcc_officer_portal/src/main/java/in/gov/chennaicorporation/gccoffice/nulm/controller/NulmAPIController.java @@ -37,57 +37,55 @@ import in.gov.chennaicorporation.gccoffice.nulm.service.NulmService; @RequestMapping("/gcc/api/nulm") @RestController("nulmAPI") public class NulmAPIController { - - private final Environment environment; - - @Autowired - private NulmService nulmService; - - @Autowired + + private final Environment environment; + + @Autowired + private NulmService nulmService; + + @Autowired private JdbcTemplate nulmJdbcTemplate; - - @Autowired - public NulmAPIController(NulmService nulmService,JdbcTemplate nulmJdbcTemplate,Environment environment) { - this.nulmService = nulmService; - this.nulmJdbcTemplate = nulmJdbcTemplate; - this.environment = environment; - } - - @Autowired - public void setDataSource(@Qualifier("mysqlNulmDataSource") DataSource dataSource) { - this.nulmJdbcTemplate = new JdbcTemplate(dataSource); - } - - - @GetMapping("/getYear") + + @Autowired + public NulmAPIController(NulmService nulmService, JdbcTemplate nulmJdbcTemplate, Environment environment) { + this.nulmService = nulmService; + this.nulmJdbcTemplate = nulmJdbcTemplate; + this.environment = environment; + } + + @Autowired + public void setDataSource(@Qualifier("mysqlNulmDataSource") DataSource dataSource) { + this.nulmJdbcTemplate = new JdbcTemplate(dataSource); + } + + @GetMapping("/getYear") public ResponseEntity>> getYear() { List> yearList = nulmService.getYearList(); return ResponseEntity.ok(yearList); } - + @GetMapping("/getMonth") public ResponseEntity>> getMonth(int year) { - //System.out.println("year: "+year); + // System.out.println("year: "+year); List> monthList = nulmService.getMonthList(year); return ResponseEntity.ok(monthList); } - + @GetMapping("/getGender") public ResponseEntity>> getGender() { - + List> genderList = nulmService.getGenderList(); return ResponseEntity.ok(genderList); } - + @GetMapping("/getDivisionList") public ResponseEntity>> getDivisionList(@RequestParam(required = false) String zone) { List> divisionList = nulmService.getDivisionList(zone); return ResponseEntity.ok(divisionList); } - - - @PostMapping("/saveGroup") - public ResponseEntity saveSchemeGroup(@RequestBody Map payload) { + + @PostMapping("/saveGroup") + public ResponseEntity saveSchemeGroup(@RequestBody Map payload) { try { Map groupData = new HashMap<>(payload); nulmService.saveSchemeGroup(groupData); @@ -96,24 +94,27 @@ public class NulmAPIController { return ResponseEntity.status(500).body("Error saving Scheme Group: " + e.getMessage()); } } - /* - @PostMapping("/saveOrder") - public ResponseEntity saveOrderDetails(@RequestBody Map payload) { - try { - Map orderData = new HashMap<>(payload); - nulmService.saveOrderDetails(orderData); - return ResponseEntity.ok("Order saved successfully."); - } catch (IllegalArgumentException e) { - return ResponseEntity.badRequest().body("Invalid data: " + e.getMessage()); - } catch (Exception e) { - return ResponseEntity.status(500).body("Error saving order: " + e.getMessage()); - } - } - */ + + /* + * @PostMapping("/saveOrder") + * public ResponseEntity saveOrderDetails(@RequestBody Map payload) { + * try { + * Map orderData = new HashMap<>(payload); + * nulmService.saveOrderDetails(orderData); + * return ResponseEntity.ok("Order saved successfully."); + * } catch (IllegalArgumentException e) { + * return ResponseEntity.badRequest().body("Invalid data: " + e.getMessage()); + * } catch (Exception e) { + * return ResponseEntity.status(500).body("Error saving order: " + + * e.getMessage()); + * } + * } + */ @PostMapping("/saveStaff") public ResponseEntity saveStaffDetails(@RequestBody Map payload) { try { - nulmService.saveStaffDetails(payload); + nulmService.saveStaffDetails(payload); return ResponseEntity.ok("Staff details saved successfully."); } catch (IllegalArgumentException e) { return ResponseEntity.badRequest().body("Error: " + e.getMessage()); @@ -121,7 +122,7 @@ public class NulmAPIController { return ResponseEntity.status(500).body("Error saving staff details: " + e.getMessage()); } } - + @PostMapping("/assignAppointment") public ResponseEntity assignOrderToEnrollments(@RequestBody Map requestBody) { int orderId = (int) requestBody.get("orderId"); @@ -142,9 +143,11 @@ public class NulmAPIController { if (orderDetails != null) { // Step 2: Build the SQL for updating enrollments with dynamic IN clause - StringBuilder updateSql = new StringBuilder("UPDATE enrollment_table SET order_id = ?, appointed = 'Yes', facial_attendance = 'No', incharge_phoneno = ?, designation = ?, appointed_date = CURRENT_DATE WHERE enrollment_id IN ("); + StringBuilder updateSql = new StringBuilder( + "UPDATE enrollment_table SET order_id = ?, appointed = 'Yes', facial_attendance = 'No', incharge_phoneno = ?, designation = ?, appointed_date = CURRENT_DATE WHERE enrollment_id IN ("); - // Add placeholders for the IN clause based on the size of the enrollmentIds list + // Add placeholders for the IN clause based on the size of the enrollmentIds + // list for (int i = 0; i < enrollmentIds.size(); i++) { updateSql.append("?"); if (i < enrollmentIds.size() - 1) { @@ -153,7 +156,8 @@ public class NulmAPIController { } updateSql.append(")"); - // Combine the orderId, inchargePhoneno, designation, and the list of enrollmentIds + // Combine the orderId, inchargePhoneno, designation, and the list of + // enrollmentIds List parameters = new ArrayList<>(); parameters.add(orderId); parameters.add(inchargePhoneno); @@ -166,13 +170,14 @@ public class NulmAPIController { return new ResponseEntity<>("Order assigned to enrollments and appointed successfully.", HttpStatus.OK); } catch (DataAccessException e) { // Handle any data access exceptions - return new ResponseEntity<>("Error updating enrollments: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); + return new ResponseEntity<>("Error updating enrollments: " + e.getMessage(), + HttpStatus.INTERNAL_SERVER_ERROR); } } return new ResponseEntity<>("Unexpected error occurred.", HttpStatus.INTERNAL_SERVER_ERROR); - } - + } + @PostMapping("/assignDropout") public ResponseEntity assignDropout(@RequestBody Map requestBody) { int orderId = (int) requestBody.get("orderId"); @@ -191,9 +196,11 @@ public class NulmAPIController { if (orderDetails != null) { // Step 2: Build the SQL for updating enrollments with dynamic IN clause - StringBuilder updateSql = new StringBuilder("UPDATE enrollment_table SET appointed = 'Drop', dropout = 'Yes', dropout_date = CURRENT_DATE WHERE enrollment_id IN ("); + StringBuilder updateSql = new StringBuilder( + "UPDATE enrollment_table SET appointed = 'Drop', dropout = 'Yes', dropout_date = CURRENT_DATE WHERE enrollment_id IN ("); - // Add placeholders for the IN clause based on the size of the enrollmentIds list + // Add placeholders for the IN clause based on the size of the enrollmentIds + // list for (int i = 0; i < enrollmentIds.size(); i++) { updateSql.append("?"); if (i < enrollmentIds.size() - 1) { @@ -210,30 +217,32 @@ public class NulmAPIController { try { int rowsAffected = nulmJdbcTemplate.update(updateSql.toString(), parameters.toArray()); if (rowsAffected > 0) { - return new ResponseEntity<>("Order assigned to enrollments has been Dropout successfully.", HttpStatus.OK); + return new ResponseEntity<>("Order assigned to enrollments has been Dropout successfully.", + HttpStatus.OK); } else { return new ResponseEntity<>("No matching records found to update.", HttpStatus.NOT_FOUND); } } catch (DataAccessException e) { // Handle any data access exceptions - return new ResponseEntity<>("Error updating enrollments: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); + return new ResponseEntity<>("Error updating enrollments: " + e.getMessage(), + HttpStatus.INTERNAL_SERVER_ERROR); } } return new ResponseEntity<>("Unexpected error occurred.", HttpStatus.INTERNAL_SERVER_ERROR); } - + @GetMapping("/getAllSchemeGroupNames") public ResponseEntity>> getAllSchemeGroupNames() { try { - List> schemeGroupNames = nulmService.getAllSchemeGroupNames(); + List> schemeGroupNames = nulmService.getAllSchemeGroupNames(); return ResponseEntity.ok(schemeGroupNames); } catch (Exception e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Collections.emptyList()); + .body(Collections.emptyList()); } } - + @GetMapping("/getAllOrderNumber") public ResponseEntity> getAllOrderNumber() { try { @@ -241,10 +250,10 @@ public class NulmAPIController { return ResponseEntity.ok(schemeGroupNames); } catch (Exception e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Collections.emptyList()); + .body(Collections.emptyList()); } } - + @GetMapping("/getAllSchemeGroups") public ResponseEntity>> getAllSchemeGroups() { try { @@ -254,18 +263,18 @@ public class NulmAPIController { return ResponseEntity.status(500).body(null); } } - - ///////get all list of orders//////////////////////////// + + /////// get all list of orders//////////////////////////// @GetMapping("/getAllOrders") public ResponseEntity>> getAllOrders() { - try { + try { List> groups = nulmService.getAllOrders(); return ResponseEntity.ok(groups); } catch (Exception e) { return ResponseEntity.status(500).body(null); } } - + @GetMapping("/getAllStaffNames") public ResponseEntity> getAllStaffNames() { try { @@ -273,10 +282,10 @@ public class NulmAPIController { return ResponseEntity.ok(schemeGroupNames); } catch (Exception e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(Collections.emptyList()); + .body(Collections.emptyList()); } } - + @GetMapping("/appointedCounts") public ResponseEntity> getAppointedCounts( @RequestParam(required = false) Integer groupId) { @@ -289,13 +298,14 @@ public class NulmAPIController { // Call the service method to get the counts Map counts = nulmService.getAppointedCounts(groupId); - + return ResponseEntity.ok(counts); } catch (Exception e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); // You can also return the error message + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); // You can also return the error + // message } } - + @PostMapping("/markAbsent") public ResponseEntity markAbsent(@RequestParam int employeeId) { int result = nulmService.markAbsentEntry(employeeId); @@ -303,10 +313,11 @@ public class NulmAPIController { if (result > 0) { return ResponseEntity.ok("Employee marked as absent successfully."); } else { - return ResponseEntity.status(304).body("No update made. Employee may already be marked as absent or has attended."); + return ResponseEntity.status(304) + .body("No update made. Employee may already be marked as absent or has attended."); } } - + @PostMapping("/markOverDuty") public ResponseEntity markOverDuty(@RequestParam int employeeId) { int result = nulmService.markOverDuty(employeeId); @@ -317,7 +328,7 @@ public class NulmAPIController { return ResponseEntity.status(304).body("No update made. Employee ID may not exist."); } } - + @PostMapping("/markAttendance") public ResponseEntity markAttendance( @RequestParam int employeeId, @@ -334,7 +345,6 @@ public class NulmAPIController { } } - @GetMapping("/getAllOrderDetails") public ResponseEntity>> getAllOrderDetails() { try { @@ -344,40 +354,40 @@ public class NulmAPIController { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Collections.emptyList()); } } - + @GetMapping("/enrollmentCountsbyorderId") public ResponseEntity> getEnrollmentCounts(@RequestParam int orderId) { Map counts = nulmService.getAppointedCounts(orderId); return ResponseEntity.ok(counts); } - - + @GetMapping("/dropOutCounts") public ResponseEntity> getDropCounts(@RequestParam int orderId) { Map counts = nulmService.getDropCounts(orderId); return ResponseEntity.ok(counts); } - + @GetMapping("/enrollmentCountsbygroupId") public ResponseEntity>> getEnrollmentbygroupId(@RequestParam int groupId) { List> enrollmentDetails = nulmService.getEnrollmentDetails(groupId); return ResponseEntity.ok(enrollmentDetails); } - + @GetMapping("/appointmentCountsbygroupId") public ResponseEntity>> getAppointedDetails(@RequestParam int groupId) { List> enrollmentDetails = nulmService.getAppointedDetails(groupId); return ResponseEntity.ok(enrollmentDetails); } - + @GetMapping("/getDepartment") public ResponseEntity>> getDepartment() { List> orderNumbers = nulmService.getDepartment(); return ResponseEntity.ok(orderNumbers); } - + @GetMapping("/getEnrollmentdeatilsByID/{enrollmentId}") - public ResponseEntity>> getEnrollmentsById(@PathVariable("enrollmentId") int enrollmentId) { + public ResponseEntity>> getEnrollmentsById( + @PathVariable("enrollmentId") int enrollmentId) { List> enrollments = nulmService.getEnrollmentsById(enrollmentId); if (enrollments.isEmpty()) { @@ -386,26 +396,26 @@ public class NulmAPIController { return ResponseEntity.ok(enrollments); // Return 200 OK with the list of enrollments } - + @GetMapping("/selfHelpGroups") public ResponseEntity>> getSelfHelpGroups() { List> selfHelpGroups = nulmService.getSelfHelpGroups(); return ResponseEntity.ok(selfHelpGroups); } - + @GetMapping("/orderNumbers") public ResponseEntity>> getOrderNumbers() { List> orderNumbers = nulmService.getOrderNumbers(); return ResponseEntity.ok(orderNumbers); } - + @PostMapping("/updateEnrollment/{id}") public ResponseEntity updateEnrollment( @PathVariable("id") int id, @RequestParam String dateOfBirth, @RequestParam String gender, @RequestParam int groupId, // New parameter - @RequestParam int orderId // New parameter + @RequestParam int orderId // New parameter ) { int rowsAffected = nulmService.updateEnrollment(id, dateOfBirth, gender, groupId, orderId); @@ -415,16 +425,16 @@ public class NulmAPIController { return new ResponseEntity<>("Enrollment update failed", HttpStatus.NOT_FOUND); } } - - @PostMapping("/saveOrder") + + @PostMapping("/saveOrder") public ResponseEntity saveOrderDetails(@RequestParam String order_number, - @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date order_date, - @RequestParam int no_of_staffs, - @RequestParam String order_description, - @RequestParam MultipartFile ordercopyurl, - @RequestParam String order_generated_by, - @RequestParam String category, - @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date validity_date) { + @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date order_date, + @RequestParam int no_of_staffs, + @RequestParam String order_description, + @RequestParam MultipartFile ordercopyurl, + @RequestParam String order_generated_by, + @RequestParam String category, + @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date validity_date) { String order_copy_url = ""; try { // Fetch the upload directory and folder name from environment @@ -435,7 +445,7 @@ public class NulmAPIController { // Construct the file path String filepath = uploadDirectory + folderName + "/" + fileName; Path path = Paths.get(filepath); - + // Ensure the directory exists Files.createDirectories(path.getParent()); @@ -447,15 +457,14 @@ public class NulmAPIController { // Save the order details using the service method String savedOrderNumber = nulmService.saveOrderDetails( - order_number, - order_date, - no_of_staffs, - order_description, - order_copy_url, - order_generated_by, - category, - validity_date - ); + order_number, + order_date, + no_of_staffs, + order_description, + order_copy_url, + order_generated_by, + category, + validity_date); return ResponseEntity.ok("Order saved successfully with order number: " + savedOrderNumber); @@ -464,199 +473,263 @@ public class NulmAPIController { return ResponseEntity.status(500).body("Error saving order: " + e.getMessage()); } } - /* - @GetMapping("/staffInititeadList") - public ResponseEntity>> getAttendanceWithInitiatedSalaryByGroupId(@RequestParam("inchargeName") String inchargeName, - @RequestParam("month") String month) { - List> staffList = nulmService.getAttendanceWithInitiatedSalary(inchargeName, month); - return ResponseEntity.ok(staffList); - } - - @GetMapping("/staffInititeadList") - public ResponseEntity>> getAttendanceWithInitiatedSalaryByGroupId( - @RequestParam(value = "inchargeId", required = false) String inchargeId, - @RequestParam(value = "month", required = false) String month, - @RequestParam(value = "inchargeName", required = false) String inchargeName, - @RequestParam(value = "zone", required = false) Integer zone) { - - List> staffList = nulmService.getAttendanceWithInitiatedSalary(inchargeId, month, inchargeName, zone); - return ResponseEntity.ok(staffList); - } - */ - - @GetMapping("/staffInititeadList") + /* + * @GetMapping("/staffInititeadList") + * public ResponseEntity>> + * getAttendanceWithInitiatedSalaryByGroupId(@RequestParam("inchargeName") + * String inchargeName, + * + * @RequestParam("month") String month) { + * List> staffList = + * nulmService.getAttendanceWithInitiatedSalary(inchargeName, month); + * return ResponseEntity.ok(staffList); + * } + * + * @GetMapping("/staffInititeadList") + * public ResponseEntity>> + * getAttendanceWithInitiatedSalaryByGroupId( + * + * @RequestParam(value = "inchargeId", required = false) String inchargeId, + * + * @RequestParam(value = "month", required = false) String month, + * + * @RequestParam(value = "inchargeName", required = false) String inchargeName, + * + * @RequestParam(value = "zone", required = false) Integer zone) { + * + * List> staffList = + * nulmService.getAttendanceWithInitiatedSalary(inchargeId, month, inchargeName, + * zone); + * return ResponseEntity.ok(staffList); + * } + */ + + @GetMapping("/staffInititeadList") public ResponseEntity>> getAttendanceWithInitiatedSalaryByGroupId( @RequestParam(value = "inchargeId", required = false) Integer inchargeId, @RequestParam(value = "month", required = false) String month, @RequestParam(value = "year", required = false) String year, @RequestParam(value = "incharge_name", required = false) String inchargeName, - @RequestParam (value = "enrollmentIds", required = false) List enrollmentIds) { + @RequestParam(value = "enrollmentIds", required = false) List enrollmentIds) { - List> staffList = nulmService.getAttendanceWithInitiatedSalary(inchargeId, month, year, inchargeName, enrollmentIds); + List> staffList = nulmService.getAttendanceWithInitiatedSalary(inchargeId, month, year, + inchargeName, enrollmentIds); return ResponseEntity.ok(staffList); } - /* - @PostMapping("/salaryDetailUpdate") - public ResponseEntity addSalaryDetails(@RequestBody List> requestList) { - System.out.println("Received POST request with data: " + requestList); - try { - for (Map request : requestList) { - int totalDaysPresent = Integer.parseInt(request.get("total_days_present").toString()); - int totalDaysOd = Integer.parseInt(request.get("total_days_od").toString()); - int totalDaysSalary = Integer.parseInt(request.get("total_days_salary").toString()); - int totalDaysAbsent = Integer.parseInt(request.get("total_days_absent").toString()); - String month = request.get("month").toString(); - int year = Integer.parseInt(request.get("year").toString()); - int salaryAmount = Integer.parseInt(request.get("salary_amount").toString()); - int enrollmentId = Integer.parseInt(request.get("enrollment_id").toString()); - int groupId = Integer.parseInt(request.get("group_id").toString()); - int wageId = Integer.parseInt(request.get("wage_id").toString()); - - // Check if the month and year are valid for salary initiation (past month) - if (isFutureOrCurrentMonth(month, year)) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST) - .body("Salary cannot be initiated for the current or future months. Please select a past month."); - } - - String salaryStatus = "Initiated"; - - // Call the service method to insert the salary details - int rowsAffected = nulmService.addSalaryDetails(totalDaysPresent, totalDaysOd, totalDaysSalary, totalDaysAbsent, month, year, salaryAmount, salaryStatus, enrollmentId, groupId, wageId); - - if (rowsAffected <= 0) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body("Failed to add salary details for enrollment ID: " + enrollmentId); - } - } - return ResponseEntity.status(HttpStatus.CREATED) - .body("Salary details added successfully for all selected entries."); - } catch (Exception e) { - e.printStackTrace(); // Log the exception for debugging - return ResponseEntity.status(HttpStatus.BAD_REQUEST) - .body("Invalid request data: " + e.getMessage()); - } - } - */ - @PostMapping("/salaryDetailUpdate") - public ResponseEntity addSalaryDetails(@RequestBody List> requestList) { - System.out.println("Received POST request with data: " + requestList); - try { - for (Map request : requestList) { - System.out.println("enrollment_id = " + request.get("enrollment_id").toString()); - int totalDaysPresent = Integer.parseInt(request.get("total_days_present").toString()); - int totalDaysOd = Integer.parseInt(request.get("total_days_od").toString()); - int totalDaysSalary = Integer.parseInt(request.get("total_days_salary").toString()); - int totalDaysAbsent = Integer.parseInt(request.get("total_days_absent").toString()); - String month = request.get("month").toString(); - int year = Integer.parseInt(request.get("year").toString()); - int salaryAmount = Integer.parseInt(request.get("salary_amount").toString()); - int enrollmentId = Integer.parseInt(request.get("enrollment_id").toString()); - int groupId = Integer.parseInt(request.get("group_id").toString()); - int wageId = Integer.parseInt(request.get("wage_id").toString()); - int inchargeID = 0;//Integer.parseInt(""+request.get("incharge_id")); - - - // Check if the month and year are valid for salary initiation (past month) - if (isFutureOrCurrentMonth(month, year)) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST) - .body("Salary cannot be initiated for the current or future months. Please select a past month."); - } - - String salaryStatus = "Initiated"; - - boolean checkexist = nulmService.checkSalaryDetails(enrollmentId, month, year); - - System.out.println("checkexist: " + checkexist); - - if (!checkexist) { - // Call the service method to insert the salary details - int rowsAffected = nulmService.addSalaryDetails(totalDaysPresent, totalDaysOd, totalDaysSalary, totalDaysAbsent, month, year, salaryAmount, salaryStatus, enrollmentId, groupId, wageId, inchargeID); - if (rowsAffected <= 0) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body("Failed to add salary details for enrollment ID: " + enrollmentId); - } - } else { - int rowsAffected = nulmService.updateSalaryDetails(totalDaysPresent, totalDaysOd, totalDaysSalary, totalDaysAbsent, month, year, salaryAmount, salaryStatus, enrollmentId, groupId, wageId, inchargeID); - if (rowsAffected <= 0) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body("Failed to update salary details for enrollment ID: " + enrollmentId); - } - } - } - return ResponseEntity.status(HttpStatus.CREATED) - .body("Salary details added successfully for all selected entries."); - } catch (Exception e) { - e.printStackTrace(); // Log the exception for debugging - return ResponseEntity.status(HttpStatus.BAD_REQUEST) - .body("Invalid request data: " + e.getMessage()); - } - } - - // Helper method to check if the month is future or current - private boolean isFutureOrCurrentMonth(String month, int year) { - // Get the current month and year - LocalDate currentDate = LocalDate.now(); - Month currentMonth = currentDate.getMonth(); - int currentYear = currentDate.getYear(); - - // Convert the string month from the request to Month enum - Month requestMonth = Month.valueOf(month.toUpperCase()); // Ensure that month is passed in capitalized format like "JANUARY", "FEBRUARY", etc. - - // Compare the request month and year with the current date - if (year > currentYear) { - return true; // Future year - } else if (year == currentYear && requestMonth.compareTo(currentMonth) >= 0) { - return true; // Current or future month in the current year - } - return false; // Past month - } - -// @PostMapping("/salaryDetailUpdate") -// public ResponseEntity addSalaryDetails(@RequestBody List> requestList) { -// System.out.println("Received POST request with data: " + requestList); -// try { -// for (Map request : requestList) { -// int totalDaysPresent = Integer.parseInt(request.get("total_days_present").toString()); -// int totalDaysOd = Integer.parseInt(request.get("total_days_od").toString()); -// int totalDaysSalary = Integer.parseInt(request.get("total_days_salary").toString()); -// int totalDaysAbsent = Integer.parseInt(request.get("total_days_absent").toString()); -// String month = request.get("month").toString(); -// int year = Integer.parseInt(request.get("year").toString()); -// int salaryAmount = Integer.parseInt(request.get("salary_amount").toString()); -// int enrollmentId = Integer.parseInt(request.get("enrollment_id").toString()); -// int groupId = Integer.parseInt(request.get("group_id").toString()); -// int wageId = Integer.parseInt(request.get("wage_id").toString()); -// -// String salaryStatus = "Initiated"; -// -// // Call the service method to insert the salary details -// int rowsAffected = nulmService.addSalaryDetails(totalDaysPresent, totalDaysOd, totalDaysSalary, totalDaysAbsent, month, year, salaryAmount, salaryStatus, enrollmentId, groupId, wageId); -// -// if (rowsAffected <= 0) { -// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to add salary details for enrollment ID: " + enrollmentId); -// } -// } -// return ResponseEntity.status(HttpStatus.CREATED).body("Salary details added successfully for all selected entries."); -// } catch (Exception e) { -// e.printStackTrace(); // Log the exception for debugging -// return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid request data: " + e.getMessage()); -// } -// } - - @PostMapping("/update-salary-status") + + /* + * @PostMapping("/salaryDetailUpdate") + * public ResponseEntity addSalaryDetails(@RequestBody List> requestList) { + * System.out.println("Received POST request with data: " + requestList); + * try { + * for (Map request : requestList) { + * int totalDaysPresent = + * Integer.parseInt(request.get("total_days_present").toString()); + * int totalDaysOd = Integer.parseInt(request.get("total_days_od").toString()); + * int totalDaysSalary = + * Integer.parseInt(request.get("total_days_salary").toString()); + * int totalDaysAbsent = + * Integer.parseInt(request.get("total_days_absent").toString()); + * String month = request.get("month").toString(); + * int year = Integer.parseInt(request.get("year").toString()); + * int salaryAmount = Integer.parseInt(request.get("salary_amount").toString()); + * int enrollmentId = Integer.parseInt(request.get("enrollment_id").toString()); + * int groupId = Integer.parseInt(request.get("group_id").toString()); + * int wageId = Integer.parseInt(request.get("wage_id").toString()); + * + * // Check if the month and year are valid for salary initiation (past month) + * if (isFutureOrCurrentMonth(month, year)) { + * return ResponseEntity.status(HttpStatus.BAD_REQUEST) + * .body("Salary cannot be initiated for the current or future months. Please select a past month." + * ); + * } + * + * String salaryStatus = "Initiated"; + * + * // Call the service method to insert the salary details + * int rowsAffected = nulmService.addSalaryDetails(totalDaysPresent, + * totalDaysOd, totalDaysSalary, totalDaysAbsent, month, year, salaryAmount, + * salaryStatus, enrollmentId, groupId, wageId); + * + * if (rowsAffected <= 0) { + * return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + * .body("Failed to add salary details for enrollment ID: " + enrollmentId); + * } + * } + * return ResponseEntity.status(HttpStatus.CREATED) + * .body("Salary details added successfully for all selected entries."); + * } catch (Exception e) { + * e.printStackTrace(); // Log the exception for debugging + * return ResponseEntity.status(HttpStatus.BAD_REQUEST) + * .body("Invalid request data: " + e.getMessage()); + * } + * } + */ + @PostMapping("/salaryDetailUpdate") + public ResponseEntity addSalaryDetails(@RequestBody List> requestList) { + System.out.println("Received POST request with data: " + requestList); + try { + for (Map request : requestList) { + System.out.println("enrollment_id = " + request.get("enrollment_id").toString()); + int totalDaysPresent = Integer.parseInt(request.get("total_days_present").toString()); + int totalDaysOd = Integer.parseInt(request.get("total_days_od").toString()); + int totalDaysSalary = Integer.parseInt(request.get("total_days_salary").toString()); + int totalDaysAbsent = Integer.parseInt(request.get("total_days_absent").toString()); + String month = request.get("month").toString(); + int year = Integer.parseInt(request.get("year").toString()); + int salaryAmount = Integer.parseInt(request.get("salary_amount").toString()); + int enrollmentId = Integer.parseInt(request.get("enrollment_id").toString()); + int groupId = Integer.parseInt(request.get("group_id").toString()); + int wageId = Integer.parseInt(request.get("wage_id").toString()); + int inchargeID = 0;// Integer.parseInt(""+request.get("incharge_id")); + + // Check if the month and year are valid for salary initiation (past month) + if (isFutureOrCurrentMonth(month, year)) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST) + .body("Salary cannot be initiated for the current or future months. Please select a past month."); + } + + String salaryStatus = "Initiated"; + + boolean checkexist = nulmService.checkSalaryDetails(enrollmentId, month, year); + + System.out.println("checkexist: " + checkexist); + + if (!checkexist) { + // Call the service method to insert the salary details + int rowsAffected = nulmService.addSalaryDetails(totalDaysPresent, totalDaysOd, totalDaysSalary, + totalDaysAbsent, month, year, salaryAmount, salaryStatus, enrollmentId, groupId, wageId, + inchargeID); + if (rowsAffected <= 0) { + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body("Failed to add salary details for enrollment ID: " + enrollmentId); + } + } else { + int rowsAffected = nulmService.updateSalaryDetails(totalDaysPresent, totalDaysOd, totalDaysSalary, + totalDaysAbsent, month, year, salaryAmount, salaryStatus, enrollmentId, groupId, wageId, + inchargeID); + if (rowsAffected <= 0) { + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body("Failed to update salary details for enrollment ID: " + enrollmentId); + } + } + } + return ResponseEntity.status(HttpStatus.CREATED) + .body("Salary details added successfully for all selected entries."); + } catch (Exception e) { + e.printStackTrace(); // Log the exception for debugging + return ResponseEntity.status(HttpStatus.BAD_REQUEST) + .body("Invalid request data: " + e.getMessage()); + } + } + + // Helper method to check if the month is future or current + private boolean isFutureOrCurrentMonth(String month, int year) { + // Get the current month and year + LocalDate currentDate = LocalDate.now(); + Month currentMonth = currentDate.getMonth(); + int currentYear = currentDate.getYear(); + + // Convert the string month from the request to Month enum + Month requestMonth = Month.valueOf(month.toUpperCase()); // Ensure that month is passed in capitalized format + // like "JANUARY", "FEBRUARY", etc. + + // Compare the request month and year with the current date + if (year > currentYear) { + return true; // Future year + } else if (year == currentYear && requestMonth.compareTo(currentMonth) >= 0) { + return true; // Current or future month in the current year + } + return false; // Past month + } + + // @PostMapping("/salaryDetailUpdate") + // public ResponseEntity addSalaryDetails(@RequestBody List> requestList) { + // System.out.println("Received POST request with data: " + requestList); + // try { + // for (Map request : requestList) { + // int totalDaysPresent = + // Integer.parseInt(request.get("total_days_present").toString()); + // int totalDaysOd = Integer.parseInt(request.get("total_days_od").toString()); + // int totalDaysSalary = + // Integer.parseInt(request.get("total_days_salary").toString()); + // int totalDaysAbsent = + // Integer.parseInt(request.get("total_days_absent").toString()); + // String month = request.get("month").toString(); + // int year = Integer.parseInt(request.get("year").toString()); + // int salaryAmount = Integer.parseInt(request.get("salary_amount").toString()); + // int enrollmentId = Integer.parseInt(request.get("enrollment_id").toString()); + // int groupId = Integer.parseInt(request.get("group_id").toString()); + // int wageId = Integer.parseInt(request.get("wage_id").toString()); + // + // String salaryStatus = "Initiated"; + // + // // Call the service method to insert the salary details + // int rowsAffected = nulmService.addSalaryDetails(totalDaysPresent, + // totalDaysOd, totalDaysSalary, totalDaysAbsent, month, year, salaryAmount, + // salaryStatus, enrollmentId, groupId, wageId); + // + // if (rowsAffected <= 0) { + // return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed + // to add salary details for enrollment ID: " + enrollmentId); + // } + // } + // return ResponseEntity.status(HttpStatus.CREATED).body("Salary details added + // successfully for all selected entries."); + // } catch (Exception e) { + // e.printStackTrace(); // Log the exception for debugging + // return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid request + // data: " + e.getMessage()); + // } + // } + + @PostMapping("/update-salary-status") public ResponseEntity updateSalaryStatus( @RequestParam List enrollmentIds, @RequestParam String month, @RequestParam int year) { - System.out.println("Enrollment IDs: " + enrollmentIds); - System.out.println("Month: " + month); - System.out.println("Year: " + year); + System.out.println("Enrollment IDs: " + enrollmentIds); + System.out.println("Month: " + month); + System.out.println("Year: " + year); nulmService.updateSalaryStatusToApproved(enrollmentIds, month, year); return ResponseEntity.ok("Salary status updated to 'Approved' for the provided enrollments."); } - - /***************API For Mobile Application*********************************/ - /* + + /*************** API For Mobile Application *********************************/ + /* + * @GetMapping("/attendanceWithSalary") + * public ResponseEntity>> + * getAttendanceWithSalaryByInchargeId( + * + * @RequestParam(value = "month", required = false) String month, + * + * @RequestParam(value = "year", required = false) Integer year, + * + * @RequestParam(value = "incharge_id", required = false) Integer inchargeId) { + * + * try { + * // Call the service method to fetch the data + * List> attendanceWithSalary = + * nulmService.getAttendanceWithSalaryByInchargeId(month, year, inchargeId); + * + * // If no data is found, return a NOT FOUND response + * if (attendanceWithSalary.isEmpty()) { + * return ResponseEntity.status(404).body(List.of(Map.of("error", + * "No attendance records found for the specified parameters."))); + * } + * + * // Return the data in the response + * return ResponseEntity.ok(attendanceWithSalary); + * } catch (Exception ex) { + * // Return a 500 Internal Server Error with the error message + * return ResponseEntity.status(500).body(List.of(Map.of("error", + * "An error occurred while fetching attendance data: " + ex.getMessage()))); + * } + * } + */ + @GetMapping("/attendanceWithSalary") public ResponseEntity>> getAttendanceWithSalaryByInchargeId( @RequestParam(value = "month", required = false) String month, @@ -664,115 +737,98 @@ public class NulmAPIController { @RequestParam(value = "incharge_id", required = false) Integer inchargeId) { try { - // Call the service method to fetch the data - List> attendanceWithSalary = nulmService.getAttendanceWithSalaryByInchargeId(month, year, inchargeId); - // If no data is found, return a NOT FOUND response + //List> attendanceWithSalary = new ArrayList<>(); + //Integer check = nulmService.checkInchargeID(inchargeId); + // if (check == 1) { + // Call the service method to fetch the data + List> attendanceWithSalary = nulmService.getAttendanceWithSalaryByInchargeId(month, year, inchargeId); + //} + // If no data is found, return a NOT FOUND response total_days_salary, + // total_salary and total_days_absent if (attendanceWithSalary.isEmpty()) { - return ResponseEntity.status(404).body(List.of(Map.of("error", "No attendance records found for the specified parameters."))); + return ResponseEntity.status(404) + .body(List.of(Map.of("error", "No attendance records found for the specified parameters."))); } - // Return the data in the response - return ResponseEntity.ok(attendanceWithSalary); - } catch (Exception ex) { - // Return a 500 Internal Server Error with the error message - return ResponseEntity.status(500).body(List.of(Map.of("error", "An error occurred while fetching attendance data: " + ex.getMessage()))); - } - } - */ - - @GetMapping("/attendanceWithSalary") - public ResponseEntity>> getAttendanceWithSalaryByInchargeId( - @RequestParam(value = "month", required = false) String month, - @RequestParam(value = "year", required = false) Integer year, - @RequestParam(value = "incharge_id", required = false) Integer inchargeId) { + for (Map aa : attendanceWithSalary) { + long days = ((Number) aa.get("total_days")).longValue(); + long present = ((Number) aa.get("total_days_present")).longValue(); + long od = ((Number) aa.get("total_days_od")).longValue(); + long salaryPerDay = ((Number) aa.get("salary_per_day")).longValue(); - try { - // Call the service method to fetch the data - List> attendanceWithSalary = nulmService.getAttendanceWithSalaryByInchargeId(month, year, inchargeId); - // If no data is found, return a NOT FOUND response total_days_salary, total_salary and total_days_absent - if (attendanceWithSalary.isEmpty()) { - return ResponseEntity.status(404).body(List.of(Map.of("error", "No attendance records found for the specified parameters."))); - } - - - for (Map aa : attendanceWithSalary) { - long days = ((Number) aa.get("total_days")).longValue(); - long present = ((Number) aa.get("total_days_present")).longValue(); - long od = ((Number) aa.get("total_days_od")).longValue(); - long salaryPerDay = ((Number) aa.get("salary_per_day")).longValue(); - - long totalPresent = present + od; - long totalAbsent = days - totalPresent; - long totalSalary = totalPresent * salaryPerDay; - - aa.put("total_salary", totalSalary); - aa.put("total_days_absent", totalAbsent); - aa.put("total_days_salary", totalPresent); - } + long totalPresent = present + od; + long totalAbsent = days - totalPresent; + long totalSalary = totalPresent * salaryPerDay; + aa.put("total_salary", totalSalary); + aa.put("total_days_absent", totalAbsent); + aa.put("total_days_salary", totalPresent); + } // Return the data in the response return ResponseEntity.ok(attendanceWithSalary); } catch (Exception ex) { // Return a 500 Internal Server Error with the error message - return ResponseEntity.status(500).body(List.of(Map.of("error", "An error occurred while fetching attendance data: " + ex.getMessage()))); + return ResponseEntity.status(500).body( + List.of(Map.of("error", "An error occurred while fetching attendance data: " + ex.getMessage()))); } } @PostMapping("/salaryDetailInitiate") public ResponseEntity addInitiatedSalaryDetails( - @RequestParam("total_days_present") List totalDaysPresentList, - @RequestParam("total_days_od") List totalDaysOdList, - @RequestParam("total_days_salary") List totalDaysSalaryList, - @RequestParam("total_days_absent") List totalDaysAbsentList, - @RequestParam("month") List monthList, - @RequestParam("year") List yearList, - @RequestParam("salary_amount") List salaryAmountList, - @RequestParam("enrollment_id") List enrollmentIdList, - @RequestParam("group_id") List groupIdList, - @RequestParam("wage_id") List wageIdList - ) { - //System.out.println("Received POST request with form-data"); - - try { - // Iterate through each list to process the form data - for (int i = 0; i < totalDaysPresentList.size(); i++) { - int totalDaysPresent = totalDaysPresentList.get(i); - int totalDaysOd = totalDaysOdList.get(i); - int total_days_salary = totalDaysSalaryList.get(i); - int totalDaysAbsent= totalDaysAbsentList.get(i); - String month = monthList.get(i); - int year = yearList.get(i); - int salaryAmount = salaryAmountList.get(i); - int enrollmentId = enrollmentIdList.get(i); - int groupId = groupIdList.get(i); - int wageId = wageIdList.get(i); - - String salaryStatus = "Initiated"; - - // Call the service method to insert the salary details - int rowsAffected = nulmService.addSalaryDetails(totalDaysPresent, totalDaysOd, total_days_salary, totalDaysAbsent, month, year, salaryAmount, salaryStatus, enrollmentId, groupId, wageId); - - if (rowsAffected <= 0) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to add salary details for enrollment ID: " + enrollmentId); - } - } - return ResponseEntity.status(HttpStatus.CREATED).body("Salary details added successfully for all selected entries."); - } catch (Exception e) { - e.printStackTrace(); // Log the exception for debugging - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid request data: " + e.getMessage()); - } - } - - -// @GetMapping("/filtered-details") -// public List> getFilteredSalaryDetails( -// @RequestParam(required = false) String month, -// @RequestParam(required = false) Integer year, -// @RequestParam(required = false) String salaryStatus) { -// -// // Call the service method to get the filtered salary details -// return nulmService.getFilteredSalaryDetails(month, year, salaryStatus); -// } + @RequestParam("total_days_present") List totalDaysPresentList, + @RequestParam("total_days_od") List totalDaysOdList, + @RequestParam("total_days_salary") List totalDaysSalaryList, + @RequestParam("total_days_absent") List totalDaysAbsentList, + @RequestParam("month") List monthList, + @RequestParam("year") List yearList, + @RequestParam("salary_amount") List salaryAmountList, + @RequestParam("enrollment_id") List enrollmentIdList, + @RequestParam("group_id") List groupIdList, + @RequestParam("wage_id") List wageIdList) { + // System.out.println("Received POST request with form-data"); + + try { + // Iterate through each list to process the form data + for (int i = 0; i < totalDaysPresentList.size(); i++) { + int totalDaysPresent = totalDaysPresentList.get(i); + int totalDaysOd = totalDaysOdList.get(i); + int total_days_salary = totalDaysSalaryList.get(i); + int totalDaysAbsent = totalDaysAbsentList.get(i); + String month = monthList.get(i); + int year = yearList.get(i); + int salaryAmount = salaryAmountList.get(i); + int enrollmentId = enrollmentIdList.get(i); + int groupId = groupIdList.get(i); + int wageId = wageIdList.get(i); + + String salaryStatus = "Initiated"; + + // Call the service method to insert the salary details + int rowsAffected = nulmService.addSalaryDetails(totalDaysPresent, totalDaysOd, total_days_salary, + totalDaysAbsent, month, year, salaryAmount, salaryStatus, enrollmentId, groupId, wageId); + + if (rowsAffected <= 0) { + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body("Failed to add salary details for enrollment ID: " + enrollmentId); + } + } + return ResponseEntity.status(HttpStatus.CREATED) + .body("Salary details added successfully for all selected entries."); + } catch (Exception e) { + e.printStackTrace(); // Log the exception for debugging + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid request data: " + e.getMessage()); + } + } + + // @GetMapping("/filtered-details") + // public List> getFilteredSalaryDetails( + // @RequestParam(required = false) String month, + // @RequestParam(required = false) Integer year, + // @RequestParam(required = false) String salaryStatus) { + // + // // Call the service method to get the filtered salary details + // return nulmService.getFilteredSalaryDetails(month, year, salaryStatus); + // } } diff --git a/gcc_officer_portal/src/main/java/in/gov/chennaicorporation/gccoffice/nulm/service/NulmService.java b/gcc_officer_portal/src/main/java/in/gov/chennaicorporation/gccoffice/nulm/service/NulmService.java index e65d25ee..dd7e9907 100644 --- a/gcc_officer_portal/src/main/java/in/gov/chennaicorporation/gccoffice/nulm/service/NulmService.java +++ b/gcc_officer_portal/src/main/java/in/gov/chennaicorporation/gccoffice/nulm/service/NulmService.java @@ -26,780 +26,842 @@ import in.gov.chennaicorporation.gccoffice.nulm.repository.NulmRepository; @Service public class NulmService { - + @Autowired private NulmRepository nulmRepository; - + @Autowired private JdbcTemplate jdbcTemplate; - + @Autowired - public NulmService(NulmRepository nulmRepository,JdbcTemplate jdbcTemplate) { + public NulmService(NulmRepository nulmRepository, JdbcTemplate jdbcTemplate) { this.nulmRepository = nulmRepository; this.jdbcTemplate = jdbcTemplate; } - + @Autowired public void setDataSource(@Qualifier("mysqlNulmDataSource") DataSource dataSource) { this.jdbcTemplate = new JdbcTemplate(dataSource); } - - public void saveOrderDetails(Map orderData) { - nulmRepository.saveOrderDetails(orderData); - } - - public void saveSchemeGroup(Map groupData) { - nulmRepository.saveSchemeGroup(groupData); - } - - public void saveStaffDetails(Map staffData) { - nulmRepository.saveStaffDetails(staffData); - } - - - public List> getYearList() { - String sql = "SELECT DISTINCT year(coalesce(indatetime,oddatetime,leavedatetime)) as year FROM attendance "; - return jdbcTemplate.queryForList(sql); - } - - public List> getMonthList(int year) { - String sql = "SELECT DISTINCT MONTHNAME(coalesce(indatetime,oddatetime,leavedatetime)) as month FROM attendance where " - + "year(coalesce(indatetime,oddatetime,leavedatetime)) = ? "; - return jdbcTemplate.queryForList(sql, year); - } - - public List> getGenderList() { - String sql = "SELECT DISTINCT(gender) as gender FROM enrollment_table "; - return jdbcTemplate.queryForList(sql); - } - - - - public List> getDivisionList(String zone) { - String sql = "SELECT DISTINCT(division) as division FROM enrollment_table where zone = ? "; - return jdbcTemplate.queryForList(sql, zone); - } - - - public void assignOrderToEnrollments(int orderId, List enrollmentIds) { - // Step 1: Retrieve the selected order - String getOrderSql = "SELECT * FROM order_details WHERE order_id = ?"; - Map orderDetails; - try { - orderDetails = jdbcTemplate.queryForMap(getOrderSql, orderId); - } catch (EmptyResultDataAccessException e) { - // Handle the case where no order is found - System.err.println("No order found with order_id: " + orderId); - return; // Exit the method if the order is not found - } - - if (orderDetails != null) { - // Step 2: Build the SQL for updating enrollments with dynamic IN clause - StringBuilder updateSql = new StringBuilder("UPDATE enrollment_table SET order_id = ?, appointed = 'Yes', facial_attendance = 'No', appointed_date = CURRENT_DATE WHERE enrollment_id IN ("); - - // Add placeholders for the IN clause based on the size of the enrollmentIds list - for (int i = 0; i < enrollmentIds.size(); i++) { - updateSql.append("?"); - if (i < enrollmentIds.size() - 1) { - updateSql.append(", "); - } - } - updateSql.append(")"); - - // Combine the orderId with the list of enrollmentIds - List parameters = new ArrayList<>(); - parameters.add(orderId); - parameters.addAll(enrollmentIds); - - // Execute the update query - try { - jdbcTemplate.update(updateSql.toString(), parameters.toArray()); - } catch (DataAccessException e) { - // Handle any data access exceptions - System.err.println("Error updating enrollments: " + e.getMessage()); - } - } - } - - - public Map getAppointedCounts(int orderId) { - // Query to get counts from the enrollment_table - String enrollmentQuery = "SELECT " + - "COUNT(CASE WHEN appointed = 'Yes' THEN 1 END) AS total_yes, " + - "COUNT(CASE WHEN appointed = 'No' THEN 1 END) AS total_no " + - "FROM enrollment_table " + - "WHERE order_id = ?"; - - // Query to get total_count from order_details - String orderDetailsQuery = "SELECT no_of_staffs AS total_count " + - "FROM order_details " + - "WHERE order_id = ?"; - - // Execute the first query - Map counts = jdbcTemplate.queryForObject(enrollmentQuery, new Object[]{orderId}, (rs, rowNum) -> { - Map result = new HashMap<>(); - result.put("total_yes", rs.getInt("total_yes")); - result.put("total_no", rs.getInt("total_no")); - return result; - }); - - // Execute the second query - Integer totalCount = jdbcTemplate.queryForObject(orderDetailsQuery, new Object[]{orderId}, Integer.class); - - // Add the total_count to the result map - counts.put("total_count", totalCount); - - // Calculate the output value: total_count - total_yes - int outputValue = totalCount - counts.get("total_yes"); - - // Add the output value to the result map - counts.put("output_value", outputValue); - - return counts; - } - - public Map getDropCounts(int orderId) { - // Query to get counts from the enrollment_table - String enrollmentQuery = "SELECT " + - "COUNT(CASE WHEN appointed = 'Yes' THEN 1 END) AS total_yes, " + - "COUNT(CASE WHEN dropout = 'Yes' THEN 1 END) AS total_drop, " + - "COUNT(CASE WHEN appointed IS NULL THEN 1 END) AS total_null " + - "FROM enrollment_table " + - "WHERE order_id = ?"; - - // Query to get total_count from order_details - String orderDetailsQuery = "SELECT no_of_staffs AS total_count " + - "FROM order_details " + - "WHERE order_id = ?"; - - // Execute the first query - Map counts = jdbcTemplate.queryForObject(enrollmentQuery, new Object[]{orderId}, (rs, rowNum) -> { - Map result = new HashMap<>(); - result.put("total_yes", rs.getInt("total_yes")); - result.put("total_drop", rs.getInt("total_drop")); - result.put("total_null", rs.getInt("total_null")); - return result; - }); - - // Execute the second query - Integer totalCount = jdbcTemplate.queryForObject(orderDetailsQuery, new Object[]{orderId}, Integer.class); - - // Add the total_count to the result map - counts.put("total_count", totalCount); - - return counts; - } - public List> getAllSchemeGroupNames() { - return nulmRepository.getAllSchemeGroupNames(); - } + public void saveOrderDetails(Map orderData) { + nulmRepository.saveOrderDetails(orderData); + } + + public void saveSchemeGroup(Map groupData) { + nulmRepository.saveSchemeGroup(groupData); + } + + public void saveStaffDetails(Map staffData) { + nulmRepository.saveStaffDetails(staffData); + } + + public List> getYearList() { + String sql = "SELECT DISTINCT year(coalesce(indatetime,oddatetime,leavedatetime)) as year FROM attendance "; + return jdbcTemplate.queryForList(sql); + } + + public List> getMonthList(int year) { + String sql = "SELECT DISTINCT MONTHNAME(coalesce(indatetime,oddatetime,leavedatetime)) as month FROM attendance where " + + "year(coalesce(indatetime,oddatetime,leavedatetime)) = ? "; + return jdbcTemplate.queryForList(sql, year); + } + + public List> getGenderList() { + String sql = "SELECT DISTINCT(gender) as gender FROM enrollment_table "; + return jdbcTemplate.queryForList(sql); + } + public List> getDivisionList(String zone) { + String sql = "SELECT DISTINCT(division) as division FROM enrollment_table where zone = ? "; + return jdbcTemplate.queryForList(sql, zone); + } - public List> getEnrollmentDetails(int groupId) { - String sql = "SELECT * FROM enrollment_table WHERE group_id = ? AND (appointed IS NULL OR appointed = 'NO')"; - return jdbcTemplate.queryForList(sql, groupId); + public void assignOrderToEnrollments(int orderId, List enrollmentIds) { + // Step 1: Retrieve the selected order + String getOrderSql = "SELECT * FROM order_details WHERE order_id = ?"; + Map orderDetails; + try { + orderDetails = jdbcTemplate.queryForMap(getOrderSql, orderId); + } catch (EmptyResultDataAccessException e) { + // Handle the case where no order is found + System.err.println("No order found with order_id: " + orderId); + return; // Exit the method if the order is not found } - - - public List> getAppointedDetails(int groupId) { - String sql = "SELECT * FROM enrollment_table WHERE group_id = ? AND (appointed IS NULL OR appointed = 'Yes')"; - return jdbcTemplate.queryForList(sql, groupId); + + if (orderDetails != null) { + // Step 2: Build the SQL for updating enrollments with dynamic IN clause + StringBuilder updateSql = new StringBuilder( + "UPDATE enrollment_table SET order_id = ?, appointed = 'Yes', facial_attendance = 'No', appointed_date = CURRENT_DATE WHERE enrollment_id IN ("); + + // Add placeholders for the IN clause based on the size of the enrollmentIds + // list + for (int i = 0; i < enrollmentIds.size(); i++) { + updateSql.append("?"); + if (i < enrollmentIds.size() - 1) { + updateSql.append(", "); + } + } + updateSql.append(")"); + + // Combine the orderId with the list of enrollmentIds + List parameters = new ArrayList<>(); + parameters.add(orderId); + parameters.addAll(enrollmentIds); + + // Execute the update query + try { + jdbcTemplate.update(updateSql.toString(), parameters.toArray()); + } catch (DataAccessException e) { + // Handle any data access exceptions + System.err.println("Error updating enrollments: " + e.getMessage()); + } } - - - public int markAbsentEntry(int employeeId) { - // Query to check if the employee has already been marked absent for today - String checkAbsentQuery = "SELECT absent FROM attendance WHERE employee_id = ? AND attendance_date = CURDATE()"; - - List absentResults = jdbcTemplate.query( - checkAbsentQuery, - ps -> ps.setInt(1, employeeId), - (rs, rowNum) -> rs.getInt("absent") - ); - - // If no record found for today, mark as absent - if (absentResults.isEmpty()) { - // Insert a new row to mark the employee as absent for today - String insertAbsentQuery = "INSERT INTO attendance (employee_id, absent, mark_attendance, attendance_date) VALUES (?, 1, 'ABSENT', CURDATE())"; - return jdbcTemplate.update(insertAbsentQuery, employeeId); - } - - // If already marked absent for today, return 0 indicating no action taken - return 0; + } + + public Map getAppointedCounts(int orderId) { + // Query to get counts from the enrollment_table + String enrollmentQuery = "SELECT " + + "COUNT(CASE WHEN appointed = 'Yes' THEN 1 END) AS total_yes, " + + "COUNT(CASE WHEN appointed = 'No' THEN 1 END) AS total_no " + + "FROM enrollment_table " + + "WHERE order_id = ?"; + + // Query to get total_count from order_details + String orderDetailsQuery = "SELECT no_of_staffs AS total_count " + + "FROM order_details " + + "WHERE order_id = ?"; + + // Execute the first query + Map counts = jdbcTemplate.queryForObject(enrollmentQuery, new Object[] { orderId }, + (rs, rowNum) -> { + Map result = new HashMap<>(); + result.put("total_yes", rs.getInt("total_yes")); + result.put("total_no", rs.getInt("total_no")); + return result; + }); + + // Execute the second query + Integer totalCount = jdbcTemplate.queryForObject(orderDetailsQuery, new Object[] { orderId }, Integer.class); + + // Add the total_count to the result map + counts.put("total_count", totalCount); + + // Calculate the output value: total_count - total_yes + int outputValue = totalCount - counts.get("total_yes"); + + // Add the output value to the result map + counts.put("output_value", outputValue); + + return counts; + } + + public Map getDropCounts(int orderId) { + // Query to get counts from the enrollment_table + String enrollmentQuery = "SELECT " + + "COUNT(CASE WHEN appointed = 'Yes' THEN 1 END) AS total_yes, " + + "COUNT(CASE WHEN dropout = 'Yes' THEN 1 END) AS total_drop, " + + "COUNT(CASE WHEN appointed IS NULL THEN 1 END) AS total_null " + + "FROM enrollment_table " + + "WHERE order_id = ?"; + + // Query to get total_count from order_details + String orderDetailsQuery = "SELECT no_of_staffs AS total_count " + + "FROM order_details " + + "WHERE order_id = ?"; + + // Execute the first query + Map counts = jdbcTemplate.queryForObject(enrollmentQuery, new Object[] { orderId }, + (rs, rowNum) -> { + Map result = new HashMap<>(); + result.put("total_yes", rs.getInt("total_yes")); + result.put("total_drop", rs.getInt("total_drop")); + result.put("total_null", rs.getInt("total_null")); + return result; + }); + + // Execute the second query + Integer totalCount = jdbcTemplate.queryForObject(orderDetailsQuery, new Object[] { orderId }, Integer.class); + + // Add the total_count to the result map + counts.put("total_count", totalCount); + + return counts; + } + + public List> getAllSchemeGroupNames() { + return nulmRepository.getAllSchemeGroupNames(); + } + + public List> getEnrollmentDetails(int groupId) { + String sql = "SELECT * FROM enrollment_table WHERE group_id = ? AND (appointed IS NULL OR appointed = 'NO')"; + return jdbcTemplate.queryForList(sql, groupId); + } + + public List> getAppointedDetails(int groupId) { + String sql = "SELECT * FROM enrollment_table WHERE group_id = ? AND (appointed IS NULL OR appointed = 'Yes')"; + return jdbcTemplate.queryForList(sql, groupId); + } + + public int markAbsentEntry(int employeeId) { + // Query to check if the employee has already been marked absent for today + String checkAbsentQuery = "SELECT absent FROM attendance WHERE employee_id = ? AND attendance_date = CURDATE()"; + + List absentResults = jdbcTemplate.query( + checkAbsentQuery, + ps -> ps.setInt(1, employeeId), + (rs, rowNum) -> rs.getInt("absent")); + + // If no record found for today, mark as absent + if (absentResults.isEmpty()) { + // Insert a new row to mark the employee as absent for today + String insertAbsentQuery = "INSERT INTO attendance (employee_id, absent, mark_attendance, attendance_date) VALUES (?, 1, 'ABSENT', CURDATE())"; + return jdbcTemplate.update(insertAbsentQuery, employeeId); } - - public int markOverDuty(int employeeId) { - // Check if the employee ID exists in the attendance table - String checkEmployeeQuery = "SELECT od FROM attendance WHERE employee_id = ?"; - - List odResults = jdbcTemplate.query( - checkEmployeeQuery, - ps -> ps.setInt(1, employeeId), - (rs, rowNum) -> rs.getInt("od") - ); - - // If the employee ID exists, update the OD field to 1 - if (!odResults.isEmpty()) { - String updateOdQuery = "UPDATE attendance SET od = 1, mark_attendance = 'OD' WHERE employee_id = ?"; - return jdbcTemplate.update(updateOdQuery, employeeId); - } - - // If the employee ID doesn't exist, return 0 to indicate no update - return 0; + + // If already marked absent for today, return 0 indicating no action taken + return 0; + } + + public int markOverDuty(int employeeId) { + // Check if the employee ID exists in the attendance table + String checkEmployeeQuery = "SELECT od FROM attendance WHERE employee_id = ?"; + + List odResults = jdbcTemplate.query( + checkEmployeeQuery, + ps -> ps.setInt(1, employeeId), + (rs, rowNum) -> rs.getInt("od")); + + // If the employee ID exists, update the OD field to 1 + if (!odResults.isEmpty()) { + String updateOdQuery = "UPDATE attendance SET od = 1, mark_attendance = 'OD' WHERE employee_id = ?"; + return jdbcTemplate.update(updateOdQuery, employeeId); } - - public List> getAllOrderDetails() { - return nulmRepository.getAllOrderDetails(); + + // If the employee ID doesn't exist, return 0 to indicate no update + return 0; + } + + public List> getAllOrderDetails() { + return nulmRepository.getAllOrderDetails(); + } + + public String markAttendance(int employeeId, String markAttendance) { + // Get today's date + LocalDate today = LocalDate.now(); + + // Query to check the current status of check_in and check_out for the employee + // on the current date + String checkAttendanceQuery = "SELECT check_in, check_out FROM attendance WHERE employee_id = ? AND attendance_date = ?"; + + List> attendanceResults = jdbcTemplate.query( + checkAttendanceQuery, + ps -> { + ps.setInt(1, employeeId); + ps.setObject(2, today); + }, + (rs, rowNum) -> { + Map result = new HashMap<>(); + result.put("check_in", rs.getInt("check_in")); + result.put("check_out", rs.getInt("check_out")); + return result; + }); + + // If the employee has not checked in today + if (attendanceResults.isEmpty()) { + if ("IN".equalsIgnoreCase(markAttendance)) { + // Mark check-in (entry phase) + String insertAttendanceQuery = "INSERT INTO attendance (employee_id, mark_attendance, check_in, in_time, attendance_date) VALUES (?, 'IN', 1, NOW(), ?)"; + jdbcTemplate.update(insertAttendanceQuery, employeeId, today); + return "Checked in successfully"; + } else { + // Trying to check out without a check-in for today + return "Failed to mark attendance - Cannot check out without checking in first"; + } } - - - public String markAttendance(int employeeId, String markAttendance) { - // Get today's date - LocalDate today = LocalDate.now(); - - // Query to check the current status of check_in and check_out for the employee on the current date - String checkAttendanceQuery = "SELECT check_in, check_out FROM attendance WHERE employee_id = ? AND attendance_date = ?"; - - List> attendanceResults = jdbcTemplate.query( - checkAttendanceQuery, - ps -> { - ps.setInt(1, employeeId); - ps.setObject(2, today); - }, - (rs, rowNum) -> { - Map result = new HashMap<>(); - result.put("check_in", rs.getInt("check_in")); - result.put("check_out", rs.getInt("check_out")); - return result; - } - ); - - // If the employee has not checked in today - if (attendanceResults.isEmpty()) { - if ("IN".equalsIgnoreCase(markAttendance)) { - // Mark check-in (entry phase) - String insertAttendanceQuery = "INSERT INTO attendance (employee_id, mark_attendance, check_in, in_time, attendance_date) VALUES (?, 'IN', 1, NOW(), ?)"; - jdbcTemplate.update(insertAttendanceQuery, employeeId, today); - return "Checked in successfully"; - } else { - // Trying to check out without a check-in for today - return "Failed to mark attendance - Cannot check out without checking in first"; - } - } - - // Retrieve the first (and only) result since attendance is checked by employee ID and date - Map result = attendanceResults.get(0); - Integer checkInStatus = (Integer) result.get("check_in"); - Integer checkOutStatus = (Integer) result.get("check_out"); - - // If the markAttendance is 'OUT' and check-in is already marked as 1 - if ("OUT".equalsIgnoreCase(markAttendance) && checkInStatus == 1 && (checkOutStatus == null || checkOutStatus == 0)) { - // Mark check-out (exit phase) - String updateCheckOutQuery = "UPDATE attendance SET check_out = 1, out_time = NOW(), mark_attendance = 'OUT' WHERE employee_id = ? AND attendance_date = ?"; - int rowsUpdated = jdbcTemplate.update(updateCheckOutQuery, employeeId, today); - if (rowsUpdated > 0) { - return "Checked out successfully"; - } else { - return "Failed to mark attendance - Could not update check-out status"; - } - } - - // If trying to check in again when already checked in - if ("IN".equalsIgnoreCase(markAttendance) && checkInStatus == 1) { - return "Failed to mark attendance - Already checked in today"; - } - - // If trying to check out but not meeting the conditions - return "Failed to mark attendance - Invalid conditions for check-out"; - } - - - public List getAllOrderNumber() { - return nulmRepository.getAllOrderNumber(); - } - - - public List> getAllSchemeGroups() { - return nulmRepository.getAllSchemeGroups(); - } - - public List> getAllOrders() { - return nulmRepository.getAllOrders(); - } - - public List getStaffName() { - return nulmRepository.getStaffName(); - } - - public List> getEnrollments(String department, String division) { - StringBuilder sql = new StringBuilder("SELECT e.*, o.order_number, s.group_name " + - "FROM enrollment_table e " + - "LEFT JOIN order_details o ON e.order_id = o.order_id " + - "LEFT JOIN suyaudavi_kuzhu s ON e.group_id = s.group_id " + - "WHERE e.appointed = '1' AND e.isactive = '1' AND e.isdelete = '0'"); - - if (department != null && !department.isEmpty()) { - sql.append(" AND e.department = '").append(department).append("'"); - } - if (division != null && !division.isEmpty()) { - sql.append(" AND e.division = '").append(division).append("'"); - } - - return jdbcTemplate.queryForList(sql.toString()); + + // Retrieve the first (and only) result since attendance is checked by employee + // ID and date + Map result = attendanceResults.get(0); + Integer checkInStatus = (Integer) result.get("check_in"); + Integer checkOutStatus = (Integer) result.get("check_out"); + + // If the markAttendance is 'OUT' and check-in is already marked as 1 + if ("OUT".equalsIgnoreCase(markAttendance) && checkInStatus == 1 + && (checkOutStatus == null || checkOutStatus == 0)) { + // Mark check-out (exit phase) + String updateCheckOutQuery = "UPDATE attendance SET check_out = 1, out_time = NOW(), mark_attendance = 'OUT' WHERE employee_id = ? AND attendance_date = ?"; + int rowsUpdated = jdbcTemplate.update(updateCheckOutQuery, employeeId, today); + if (rowsUpdated > 0) { + return "Checked out successfully"; + } else { + return "Failed to mark attendance - Could not update check-out status"; + } } - - public List> getDepartment() { - String sql = "SELECT DISTINCT department FROM enrollment_table WHERE isactive = 1 AND isdelete = 0"; - return jdbcTemplate.queryForList(sql); + + // If trying to check in again when already checked in + if ("IN".equalsIgnoreCase(markAttendance) && checkInStatus == 1) { + return "Failed to mark attendance - Already checked in today"; } - - public List> getDivision() { - String sql = "SELECT DISTINCT division FROM enrollment_table WHERE isactive = 1 AND isdelete = 0"; - return jdbcTemplate.queryForList(sql); + + // If trying to check out but not meeting the conditions + return "Failed to mark attendance - Invalid conditions for check-out"; + } + + public List getAllOrderNumber() { + return nulmRepository.getAllOrderNumber(); + } + + public List> getAllSchemeGroups() { + return nulmRepository.getAllSchemeGroups(); + } + + public List> getAllOrders() { + return nulmRepository.getAllOrders(); + } + + public List getStaffName() { + return nulmRepository.getStaffName(); + } + + public List> getEnrollments(String department, String division) { + StringBuilder sql = new StringBuilder("SELECT e.*, o.order_number, s.group_name " + + "FROM enrollment_table e " + + "LEFT JOIN order_details o ON e.order_id = o.order_id " + + "LEFT JOIN suyaudavi_kuzhu s ON e.group_id = s.group_id " + + "WHERE e.appointed = '1' AND e.isactive = '1' AND e.isdelete = '0'"); + + if (department != null && !department.isEmpty()) { + sql.append(" AND e.department = '").append(department).append("'"); } - - public List> getEnrollmentsById(int enrollmentId) { - String sql = "SELECT * FROM enrollment_table " + - "WHERE enrollment_id = ? " + - "AND isactive = 1 " + - "AND isdelete = 0 " + - "AND (appointed = 1 OR appointed IS NULL) " + - "AND (dropout = 0 OR dropout IS NULL) "; - - try { - // Query the database for enrollment details based on the specified conditions and enrollment_id - return jdbcTemplate.queryForList(sql, new Object[]{enrollmentId}); - } catch (Exception e) { - // Return an empty list if no enrollments are found - return List.of(); - } + if (division != null && !division.isEmpty()) { + sql.append(" AND e.division = '").append(division).append("'"); } - - public List> getSelfHelpGroups() { - String sql = "SELECT group_id AS groupId, group_name AS groupName FROM suyaudavi_kuzhu WHERE isactive = 1 AND isdelete = 0 order by group_name asc"; - return jdbcTemplate.queryForList(sql); + + return jdbcTemplate.queryForList(sql.toString()); } - - public List> getOrderNumbers() { - String sql = "SELECT order_id AS orderId, order_number AS orderNumber FROM order_details WHERE isactive = 1 AND isdelete = 0"; - return jdbcTemplate.queryForList(sql); + + public List> getDepartment() { + String sql = "SELECT DISTINCT department FROM enrollment_table WHERE isactive = 1 AND isdelete = 0"; + return jdbcTemplate.queryForList(sql); } - - public int updateEnrollment( - int enrollmentId, - String dateOfBirth, - String gender, - int groupId, // New parameter - int orderId // New parameter - ) { - String sql = "UPDATE enrollment_table SET date_of_birth = ?, gender = ?, group_id = ?, order_id = ? WHERE enrollment_id = ?"; - return jdbcTemplate.update(sql, dateOfBirth, gender, groupId, orderId, enrollmentId); + public List> getDivision() { + String sql = "SELECT DISTINCT division FROM enrollment_table WHERE isactive = 1 AND isdelete = 0"; + return jdbcTemplate.queryForList(sql); } - - /* - public String saveOrderDetails(String order_number, Date order_date, int no_of_staffs, String order_description, String order_copy_url, String order_generated_by, String category, Date validity_date) { - String sql = "INSERT INTO order_details (order_number, order_date, no_of_staffs, order_description, order_copy_url, order_generated_by, category, created_date, validity_date, order_status, isactive, isdelete) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP, ?, CASE WHEN ? >= ? THEN 'Active' ELSE 'Expired' END, 1, 0)"; - - try { - // Parameters array to be passed to the update method - Object[] params = new Object[] { - order_number, - order_date, - no_of_staffs, - order_description, - order_copy_url, - order_generated_by, - category, - validity_date, - validity_date, // For the CASE WHEN condition - new Date() // Current date for comparison with validity_date - }; - - // Execute the update - jdbcTemplate.update(sql, params); - - return order_number; - } catch (Exception e) { - e.printStackTrace(); - return "Error in Saving Order Details, give proper input"; - } + + public List> getEnrollmentsById(int enrollmentId) { + String sql = "SELECT * FROM enrollment_table " + + "WHERE enrollment_id = ? " + + "AND isactive = 1 " + + "AND isdelete = 0 " + + "AND (appointed = 1 OR appointed IS NULL) " + + "AND (dropout = 0 OR dropout IS NULL) "; + + try { + // Query the database for enrollment details based on the specified conditions + // and enrollment_id + return jdbcTemplate.queryForList(sql, new Object[] { enrollmentId }); + } catch (Exception e) { + // Return an empty list if no enrollments are found + return List.of(); + } } - */ - - public String saveOrderDetails(String order_number, Date order_date, int no_of_staffs, String order_description, String order_copy_url, String order_generated_by, String category, Date validity_date) { - String sql = "INSERT INTO order_details (order_number, order_date, no_of_staffs, order_description, order_copy_url, order_generated_by, category, created_date, validity_date, order_status, isactive, isdelete) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP, ?, CASE WHEN ? >= ? THEN 'Active' ELSE 'Expired' END, 1, 0)"; - - try { - // Parameters array to be passed to the update method - Object[] params = new Object[] { - order_number, - order_date, - no_of_staffs, - order_description, - order_copy_url, - order_generated_by, - category, - validity_date, - validity_date, // For the CASE WHEN condition - order_date // Comparison with order_date instead of the current date - }; - - // Log the SQL query for debugging - System.out.println("INSERT INTO order_details (order_number, order_date, no_of_staffs, order_description, order_copy_url, order_generated_by, category, created_date, validity_date, order_status, isactive, isdelete) " + - "VALUES ('" + order_number + "', '" + order_date + "', '" + no_of_staffs + "', '" + order_description + "', '" + order_copy_url + "', '" + order_generated_by + "', '" + category + "', CURRENT_TIMESTAMP, " + - validity_date + ", CASE WHEN " + validity_date + " >= " + order_date + " THEN 'Active' ELSE 'Expired' END, 1, 0)"); - - // Execute the update - jdbcTemplate.update(sql, params); - - return order_number; - } catch (Exception e) { - e.printStackTrace(); - return "Error in Saving Order Details, give proper input"; - } + + public List> getSelfHelpGroups() { + String sql = "SELECT group_id AS groupId, group_name AS groupName FROM suyaudavi_kuzhu WHERE isactive = 1 AND isdelete = 0 order by group_name asc"; + return jdbcTemplate.queryForList(sql); } - - public int addSalaryDetails(int totalDaysPresent, int totalDaysOd, int totalDaysSalary, int totalDaysAbsent, String month, int year, int salaryAmount, - String salaryStatus, int enrollmentId, int groupId, int wageId) { - String sql = "INSERT INTO salary_details (total_days_present, total_days_od, total_days_salary, total_days_absent, month, year, salary_amount, salary_status, enrollment_id, group_id, wage_id) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - - return jdbcTemplate.update(sql, totalDaysPresent, totalDaysOd, totalDaysSalary, totalDaysAbsent, month, year, salaryAmount, salaryStatus, enrollmentId, groupId, wageId); + + public List> getOrderNumbers() { + String sql = "SELECT order_id AS orderId, order_number AS orderNumber FROM order_details WHERE isactive = 1 AND isdelete = 0"; + return jdbcTemplate.queryForList(sql); } - - public List> getAttendanceWithSalary(String month, Integer year) { - StringBuilder sql = new StringBuilder("SELECT " + - "e.enrollment_id, " + - "e.name, " + - "e.incharge_id, " + - "YEAR(coalesce((a.indatetime),(a.oddatetime),(a.leavedatetime))) AS year, " + - "MONTHNAME(coalesce((a.indatetime),(a.oddatetime),(a.leavedatetime))) AS month, " + - "COUNT(DISTINCT DATE(a.indatetime)) AS total_days_present, " + - "COUNT(DISTINCT DATE(a.leavedatetime)) AS total_days_absent, " + - "COUNT(DISTINCT CASE WHEN a.indatetime IS NULL THEN DATE(a.oddatetime) END) AS total_days_od, " + - "COUNT(DISTINCT DATE(a.indatetime)) + " + - "COUNT(DISTINCT DATE(a.leavedatetime)) + " + - "COUNT(DISTINCT CASE WHEN a.indatetime IS NULL THEN DATE(a.oddatetime) END) AS total_days, " + - "COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT CASE WHEN a.indatetime IS NULL THEN DATE(a.oddatetime) END) AS total_days_salary, " + - "(SELECT sw.wage_id FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1) AS wage_id, " + - "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1) AS salary_per_day, " + - "((COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT CASE WHEN a.indatetime IS NULL THEN DATE(a.oddatetime) END)) * " + - "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1)) AS total_salary, " + - "sd.salary_status, " + - "sk.group_id, " + - "sk.group_name " + - "FROM enrollment_table e " + - "LEFT JOIN attendance a ON e.enrollment_id = a.enrollment_id " + // Changed JOIN to LEFT JOIN to include all enrollments - "LEFT JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " + - "AND YEAR(a.indatetime and a.oddatetime and a.leavedatetime) = sd.year " + - "AND MONTHNAME(a.indatetime and a.oddatetime and a.leavedatetime) = sd.month " + - "LEFT JOIN suyaudavi_kuzhu sk ON e.group_id = sk.group_id " + - "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) "); - - // Add month condition if month is provided - if (month != null && !month.isEmpty()) { - sql.append("AND MONTHNAME(coalesce((a.indatetime),(a.leavedatetime),(a.oddatetime)))= ? "); - } - - // Add year condition if year is provided - if (year != null) { - sql.append("AND YEAR(coalesce((a.indatetime),(a.leavedatetime),(a.oddatetime))) = ? "); - } - - sql.append("GROUP BY e.enrollment_id, YEAR(coalesce((a.indatetime),(a.oddatetime),(a.leavedatetime))), " - + "MONTHNAME(coalesce((a.indatetime),(a.oddatetime),(a.leavedatetime))), sd.salary_status "); - - // Create a list of parameters to pass to the query - List params = new ArrayList<>(); - if (month != null && !month.isEmpty()) { - params.add(month); - } - if (year != null) { - params.add(year); - } - - // Execute the query with the provided parameters - List> results = jdbcTemplate.queryForList(sql.toString(), params.toArray()); - //List> results = jdbcTemplate.queryForList(sql.toString()); - return results; + + public int updateEnrollment( + int enrollmentId, + String dateOfBirth, + String gender, + int groupId, // New parameter + int orderId // New parameter + ) { + String sql = "UPDATE enrollment_table SET date_of_birth = ?, gender = ?, group_id = ?, order_id = ? WHERE enrollment_id = ?"; + + return jdbcTemplate.update(sql, dateOfBirth, gender, groupId, orderId, enrollmentId); } -/* - public List> getAttendanceWithSalaryByInchargeId(String month, Integer year, Integer incharge_id) { - String sql = "SELECT e.enrollment_id, e.emp_id, COALESCE(e.name, '') AS name, YEAR(a.indatetime) AS year, " - + "MONTHNAME(a.indatetime) AS month, COUNT(a.inby) AS total_days_present, " - + "COUNT(a.leaveby) AS total_days_absent, COUNT(a.odby) AS total_days_od, " - + "(COUNT(a.inby) + COUNT(a.leaveby) + COUNT(a.odby)) AS total_days, " - + "(COUNT(a.inby) + COUNT(a.odby)) AS total_days_salary, " - + "COALESCE((SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1), 0) AS salary_per_day, " - + "COALESCE(((COUNT(a.inby) + COUNT(a.odby)) * (SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1)), 0) AS total_salary, " - + "COALESCE(sd.salary_status, '') AS salary_status, COALESCE(sk.group_id, '') AS group_id, " - + "COALESCE(sk.group_name, '') AS group_name " - + "FROM enrollment_table e " - + "JOIN attendance a ON e.enrollment_id = a.enrollment_id " - + "LEFT JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " - + "AND YEAR(a.indatetime) = sd.year AND MONTHNAME(a.indatetime) = sd.month " - + "LEFT JOIN suyaudavi_kuzhu sk ON e.group_id = sk.group_id " - + "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) " - + "AND e.incharge_id = '" + incharge_id + "' " - + "AND MONTHNAME(a.indatetime) = '" + month + "' " - + "AND YEAR(a.indatetime) = '" + year + "' " - + "GROUP BY e.enrollment_id, e.name, YEAR(a.indatetime), MONTHNAME(a.indatetime), " - + "sd.salary_status, sk.group_id, sk.group_name"; - - System.out.println(sql); - - // Execute the query with the provided parameters - List> results = jdbcTemplate.queryForList(sql); - return results; - } - - public List> getAttendanceWithSalary(String month, Integer year) { - StringBuilder sql = new StringBuilder("SELECT " + - "e.enrollment_id, " + - "e.name, " + - "YEAR(a.indatetime) AS year, " + - "MONTHNAME(a.indatetime) AS month, " + - "COUNT(a.inby) AS total_days_present, " + - "COUNT(a.leaveby) AS total_days_absent, " + - "COUNT(a.odby) AS total_days_od, " + - "(COUNT(a.inby) + COUNT(a.leaveby) + COUNT(a.odby)) AS total_days, " + - "(COUNT(a.inby) + COUNT(a.odby)) AS total_days_salary, " + - "(SELECT sw.wage_id FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1) AS wage_id, " + - "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1) AS salary_per_day, " + - "((COUNT(a.inby) + COUNT(a.odby)) * " + - "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1)) AS total_salary, " + - "sd.salary_status, " + - "sk.group_id, " + - "sk.group_name " + - "FROM enrollment_table e " + - "JOIN attendance a ON e.enrollment_id = a.enrollment_id " + - "LEFT JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " + - "AND YEAR(a.indatetime) = sd.year " + - "AND MONTHNAME(a.indatetime) = sd.month " + - "LEFT JOIN suyaudavi_kuzhu sk ON e.group_id = sk.group_id " + - "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) "); - - // Add month condition if month is provided - if (month != null && !month.isEmpty()) { - sql.append("AND MONTHNAME(a.indatetime) = ? "); - } - - // Add year condition if year is provided - if (year != null) { - sql.append("AND YEAR(a.indatetime) = ? "); - } - - sql.append("GROUP BY e.enrollment_id, e.name, YEAR(a.indatetime), MONTHNAME(a.indatetime), sd.salary_status, sk.group_id, sk.group_name"); - - // Create a list of parameters to pass to the query - List params = new ArrayList<>(); - if (month != null && !month.isEmpty()) { - params.add(month); - } - if (year != null) { - params.add(year); - } - - // Execute the query with the provided parameters - List> results = jdbcTemplate.queryForList(sql.toString(), params.toArray()); - return results; + + /* + * public String saveOrderDetails(String order_number, Date order_date, int + * no_of_staffs, String order_description, String order_copy_url, String + * order_generated_by, String category, Date validity_date) { + * String sql = + * "INSERT INTO order_details (order_number, order_date, no_of_staffs, order_description, order_copy_url, order_generated_by, category, created_date, validity_date, order_status, isactive, isdelete) " + * + + * "VALUES (?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP, ?, CASE WHEN ? >= ? THEN 'Active' ELSE 'Expired' END, 1, 0)" + * ; + * + * try { + * // Parameters array to be passed to the update method + * Object[] params = new Object[] { + * order_number, + * order_date, + * no_of_staffs, + * order_description, + * order_copy_url, + * order_generated_by, + * category, + * validity_date, + * validity_date, // For the CASE WHEN condition + * new Date() // Current date for comparison with validity_date + * }; + * + * // Execute the update + * jdbcTemplate.update(sql, params); + * + * return order_number; + * } catch (Exception e) { + * e.printStackTrace(); + * return "Error in Saving Order Details, give proper input"; + * } + * } + */ + + public String saveOrderDetails(String order_number, Date order_date, int no_of_staffs, String order_description, + String order_copy_url, String order_generated_by, String category, Date validity_date) { + String sql = "INSERT INTO order_details (order_number, order_date, no_of_staffs, order_description, order_copy_url, order_generated_by, category, created_date, validity_date, order_status, isactive, isdelete) " + + + "VALUES (?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP, ?, CASE WHEN ? >= ? THEN 'Active' ELSE 'Expired' END, 1, 0)"; + + try { + // Parameters array to be passed to the update method + Object[] params = new Object[] { + order_number, + order_date, + no_of_staffs, + order_description, + order_copy_url, + order_generated_by, + category, + validity_date, + validity_date, // For the CASE WHEN condition + order_date // Comparison with order_date instead of the current date + }; + + // Log the SQL query for debugging + System.out.println( + "INSERT INTO order_details (order_number, order_date, no_of_staffs, order_description, order_copy_url, order_generated_by, category, created_date, validity_date, order_status, isactive, isdelete) " + + + "VALUES ('" + order_number + "', '" + order_date + "', '" + no_of_staffs + "', '" + + order_description + "', '" + order_copy_url + "', '" + order_generated_by + "', '" + + category + "', CURRENT_TIMESTAMP, " + + validity_date + ", CASE WHEN " + validity_date + " >= " + order_date + + " THEN 'Active' ELSE 'Expired' END, 1, 0)"); + + // Execute the update + jdbcTemplate.update(sql, params); + + return order_number; + } catch (Exception e) { + e.printStackTrace(); + return "Error in Saving Order Details, give proper input"; + } } - - public List> getSalaryReport(String month, int year, String salaryStatus,String loginId) { - - // Retrieve zone access for the user - String ZoneWhare; - String zoneAccessSQL = "SELECT zone FROM gcc_apps.login_mapping_user WHERE appuser_id = ?"; - List> getAccess = jdbcTemplate.queryForList(zoneAccessSQL, loginId); - System.out.println(zoneAccessSQL +"->"+ loginId); - // Extract the zones from getAccess - List zones = getAccess.stream() - .map(access -> (String) access.get("zone")) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - - // If the user has zone acc ess, add it to the WHERE clause - if (!zones.isEmpty()) { - String zoneList = zones.stream() - .map(zone -> "'" + zone + "'") - .collect(Collectors.joining(", ")); - ZoneWhare = " AND e.zone IN ("+zoneList+")"; - // System.out.println("AND e.zone IN ("+zoneList+")"); - } - else { - ZoneWhare = " AND e.zone IN (0)"; - } - - String sql = "SELECT " + - "e.enrollment_id, " + - "e.emp_id, " + - "e.name, " + - "e.incharge_name, " + // Fetch incharge_name from enrollment_table - "e.incharge_designation, " + // Fetch incharge_designation from enrollment_table - "YEAR(a.indatetime) AS year, " + - "MONTHNAME(a.indatetime) AS month, " + // Use MONTHNAME to get month in words - "COUNT(a.inby) AS total_days_present, " + - "COUNT(a.leaveby) AS total_days_absent, " + // Changed to total_days_absent - "COUNT(a.odby) AS total_days_od, " + - "(COUNT(a.inby) + COUNT(a.odby)) AS total_days_salary, " + - "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1) AS salary_per_day, " + // Fetch salary_per_day from staff_wages table - "((COUNT(a.inby) + COUNT(a.odby)) * " + - "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1)) AS total_salary, " + // Calculate total salary - "sd.salary_status, " + - "sk.group_id, " + // Fetch group_id from suyaudavi_kuzhu table - "sk.group_name " + // Fetch group_name from suyaudavi_kuzhu table - "FROM enrollment_table e " + - "JOIN attendance a ON e.enrollment_id = a.enrollment_id " + - "LEFT JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " + - "AND YEAR(a.indatetime) = sd.year " + // Match year - "AND MONTHNAME(a.indatetime) = sd.month " + // Match month name - "LEFT JOIN suyaudavi_kuzhu sk ON e.group_id = sk.group_id " + // Join with suyaudavi_kuzhu table on group_id - "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) " + // Removed unauthorizedleaveby - "AND MONTHNAME(a.indatetime) = ? " + // Filter by month - "AND YEAR(a.indatetime) = ? "+ // Filter by year - "AND (sd.salary_status = 'Initiated' OR sd.salary_status = 'Approved') " + // Filter by year - (salaryStatus != null && !salaryStatus.isEmpty() ? "AND sd.salary_status = ? " : "") + // Optional filter by salary status - ZoneWhare +" GROUP BY e.enrollment_id, e.name, e.incharge_name, e.incharge_designation, YEAR(a.indatetime), MONTHNAME(a.indatetime), salary_per_day, sd.salary_status, sk.group_id, sk.group_name"; // Group by new fields - - // Prepare the query parameters based on provided inputs - List params = new ArrayList<>(); - params.add(month); - params.add(year); - if (salaryStatus != null && !salaryStatus.isEmpty()) { - params.add(salaryStatus); - } - - // Execute the query with dynamic parameters - List> results = jdbcTemplate.queryForList(sql, params.toArray()); - return results; + + public int addSalaryDetails(int totalDaysPresent, int totalDaysOd, int totalDaysSalary, int totalDaysAbsent, + String month, int year, int salaryAmount, + String salaryStatus, int enrollmentId, int groupId, int wageId) { + String sql = "INSERT INTO salary_details (total_days_present, total_days_od, total_days_salary, total_days_absent, month, year, salary_amount, salary_status, enrollment_id, group_id, wage_id) " + + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; + + return jdbcTemplate.update(sql, totalDaysPresent, totalDaysOd, totalDaysSalary, totalDaysAbsent, month, year, + salaryAmount, salaryStatus, enrollmentId, groupId, wageId); } - */ - - /* - public List> getSalaryReport(String month, int year, String salaryStatus,String loginId) { - - // Retrieve zone access for the user - String ZoneWhare; - String zoneAccessSQL = "SELECT zone FROM gcc_apps.login_mapping_user WHERE appuser_id = ?"; - List> getAccess = jdbcTemplate.queryForList(zoneAccessSQL, loginId); - System.out.println(zoneAccessSQL +"->"+ loginId); - // Extract the zones from getAccess - List zones = getAccess.stream() - .map(access -> (String) access.get("zone")) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - - // If the user has zone acc ess, add it to the WHERE clause - if (!zones.isEmpty()) { - String zoneList = zones.stream() - .map(zone -> "'" + zone + "'") - .collect(Collectors.joining(", ")); - ZoneWhare = " AND e.zone IN ("+zoneList+")"; - // System.out.println("AND e.zone IN ("+zoneList+")"); - } - else { - ZoneWhare = " AND e.zone IN (0)"; - } - - String sql = "SELECT " + - "e.enrollment_id, " + - "e.emp_id, " + - "e.name, " + - "e.incharge_name, " + // Fetch incharge_name from enrollment_table - "e.incharge_designation, " + // Fetch incharge_designation from enrollment_table - "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS iyear, " + - "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS imonth, " + // Use MONTHNAME to get month in words - "COUNT(DISTINCT DATE(a.indatetime)) AS total_days_present, " + - "COUNT(DISTINCT DATE(a.leavedatetime)) AS total_days_absent, " + // Changed to total_days_absent - "COUNT(DISTINCT DATE(a.oddatetime)) AS total_days_od, " + - "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) AS total_days_salary, " + - "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1) AS salary_per_day, " + // Fetch salary_per_day from staff_wages table - "((COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) * " + - "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1)) AS total_salary, " + // Calculate total salary - "sd.salary_status, " + - "sk.group_id, " + // Fetch group_id from suyaudavi_kuzhu table - "sk.group_name " + // Fetch group_name from suyaudavi_kuzhu table - "FROM enrollment_table e " + - "JOIN attendance a ON e.enrollment_id = a.enrollment_id " + - "LEFT JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " + - "AND YEAR(a.indatetime) = sd.year " + // Match year - "AND MONTHNAME(a.indatetime) = sd.month " + // Match month name - "LEFT JOIN suyaudavi_kuzhu sk ON e.group_id = sk.group_id " + // Join with suyaudavi_kuzhu table on group_id - "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) " + // Removed unauthorizedleaveby - "AND MONTHNAME(a.indatetime) = ? " + // Filter by month - "AND YEAR(a.indatetime) = ? "+ // Filter by year - "AND (sd.salary_status = 'Initiated' OR sd.salary_status = 'Approved') " + // Filter by year - (salaryStatus != null && !salaryStatus.isEmpty() ? "AND sd.salary_status = ? " : "") + // Optional filter by salary status - ZoneWhare +" GROUP BY e.enrollment_id, e.name, e.incharge_name, e.incharge_designation, iyear, imonth, salary_per_day, sd.salary_status, sk.group_id, sk.group_name"; // Group by new fields - - // Prepare the query parameters based on provided inputs - List params = new ArrayList<>(); - params.add(month); - params.add(year); - if (salaryStatus != null && !salaryStatus.isEmpty()) { - params.add(salaryStatus); - } - - // Execute the query with dynamic parameters - List> results = jdbcTemplate.queryForList(sql, params.toArray()); - return results; + + public List> getAttendanceWithSalary(String month, Integer year) { + StringBuilder sql = new StringBuilder("SELECT " + + "e.enrollment_id, " + + "e.name, " + + "e.incharge_id, " + + "YEAR(coalesce((a.indatetime),(a.oddatetime),(a.leavedatetime))) AS year, " + + "MONTHNAME(coalesce((a.indatetime),(a.oddatetime),(a.leavedatetime))) AS month, " + + "COUNT(DISTINCT DATE(a.indatetime)) AS total_days_present, " + + "COUNT(DISTINCT DATE(a.leavedatetime)) AS total_days_absent, " + + "COUNT(DISTINCT CASE WHEN a.indatetime IS NULL THEN DATE(a.oddatetime) END) AS total_days_od, " + + "COUNT(DISTINCT DATE(a.indatetime)) + " + + "COUNT(DISTINCT DATE(a.leavedatetime)) + " + + "COUNT(DISTINCT CASE WHEN a.indatetime IS NULL THEN DATE(a.oddatetime) END) AS total_days, " + + "COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT CASE WHEN a.indatetime IS NULL THEN DATE(a.oddatetime) END) AS total_days_salary, " + + + "(SELECT sw.wage_id FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1) AS wage_id, " + + + "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1) AS salary_per_day, " + + + "((COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT CASE WHEN a.indatetime IS NULL THEN DATE(a.oddatetime) END)) * " + + + "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1)) AS total_salary, " + + + "sd.salary_status, " + + "sk.group_id, " + + "sk.group_name " + + "FROM enrollment_table e " + + "LEFT JOIN attendance a ON e.enrollment_id = a.enrollment_id " + // Changed JOIN to LEFT JOIN to include + // all enrollments + "LEFT JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " + + "AND YEAR(a.indatetime and a.oddatetime and a.leavedatetime) = sd.year " + + "AND MONTHNAME(a.indatetime and a.oddatetime and a.leavedatetime) = sd.month " + + "LEFT JOIN suyaudavi_kuzhu sk ON e.group_id = sk.group_id " + + "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) "); + + // Add month condition if month is provided + if (month != null && !month.isEmpty()) { + sql.append("AND MONTHNAME(coalesce((a.indatetime),(a.leavedatetime),(a.oddatetime)))= ? "); + } + + // Add year condition if year is provided + if (year != null) { + sql.append("AND YEAR(coalesce((a.indatetime),(a.leavedatetime),(a.oddatetime))) = ? "); + } + + sql.append("GROUP BY e.enrollment_id, YEAR(coalesce((a.indatetime),(a.oddatetime),(a.leavedatetime))), " + + "MONTHNAME(coalesce((a.indatetime),(a.oddatetime),(a.leavedatetime))), sd.salary_status "); + + // Create a list of parameters to pass to the query + List params = new ArrayList<>(); + if (month != null && !month.isEmpty()) { + params.add(month); + } + if (year != null) { + params.add(year); + } + + // Execute the query with the provided parameters + List> results = jdbcTemplate.queryForList(sql.toString(), params.toArray()); + // List> results = + // jdbcTemplate.queryForList(sql.toString()); + return results; } - */ - public List> getSalaryReport(String month, Integer year, String salaryStatus, String groupName, String loginId) { + /* + * public List> getAttendanceWithSalaryByInchargeId(String + * month, Integer year, Integer incharge_id) { + * String sql = + * "SELECT e.enrollment_id, e.emp_id, COALESCE(e.name, '') AS name, YEAR(a.indatetime) AS year, " + * + "MONTHNAME(a.indatetime) AS month, COUNT(a.inby) AS total_days_present, " + * + "COUNT(a.leaveby) AS total_days_absent, COUNT(a.odby) AS total_days_od, " + * + "(COUNT(a.inby) + COUNT(a.leaveby) + COUNT(a.odby)) AS total_days, " + * + "(COUNT(a.inby) + COUNT(a.odby)) AS total_days_salary, " + * + + * "COALESCE((SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1), 0) AS salary_per_day, " + * + + * "COALESCE(((COUNT(a.inby) + COUNT(a.odby)) * (SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1)), 0) AS total_salary, " + * + + * "COALESCE(sd.salary_status, '') AS salary_status, COALESCE(sk.group_id, '') AS group_id, " + * + "COALESCE(sk.group_name, '') AS group_name " + * + "FROM enrollment_table e " + * + "JOIN attendance a ON e.enrollment_id = a.enrollment_id " + * + "LEFT JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " + * + "AND YEAR(a.indatetime) = sd.year AND MONTHNAME(a.indatetime) = sd.month " + * + "LEFT JOIN suyaudavi_kuzhu sk ON e.group_id = sk.group_id " + * + + * "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) " + * + "AND e.incharge_id = '" + incharge_id + "' " + * + "AND MONTHNAME(a.indatetime) = '" + month + "' " + * + "AND YEAR(a.indatetime) = '" + year + "' " + * + + * "GROUP BY e.enrollment_id, e.name, YEAR(a.indatetime), MONTHNAME(a.indatetime), " + * + "sd.salary_status, sk.group_id, sk.group_name"; + * + * System.out.println(sql); + * + * // Execute the query with the provided parameters + * List> results = jdbcTemplate.queryForList(sql); + * return results; + * } + * + * public List> getAttendanceWithSalary(String month, + * Integer year) { + * StringBuilder sql = new StringBuilder("SELECT " + + * "e.enrollment_id, " + + * "e.name, " + + * "YEAR(a.indatetime) AS year, " + + * "MONTHNAME(a.indatetime) AS month, " + + * "COUNT(a.inby) AS total_days_present, " + + * "COUNT(a.leaveby) AS total_days_absent, " + + * "COUNT(a.odby) AS total_days_od, " + + * "(COUNT(a.inby) + COUNT(a.leaveby) + COUNT(a.odby)) AS total_days, " + + * "(COUNT(a.inby) + COUNT(a.odby)) AS total_days_salary, " + + * "(SELECT sw.wage_id FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1) AS wage_id, " + * + + * "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1) AS salary_per_day, " + * + + * "((COUNT(a.inby) + COUNT(a.odby)) * " + + * "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1)) AS total_salary, " + * + + * "sd.salary_status, " + + * "sk.group_id, " + + * "sk.group_name " + + * "FROM enrollment_table e " + + * "JOIN attendance a ON e.enrollment_id = a.enrollment_id " + + * "LEFT JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " + + * "AND YEAR(a.indatetime) = sd.year " + + * "AND MONTHNAME(a.indatetime) = sd.month " + + * "LEFT JOIN suyaudavi_kuzhu sk ON e.group_id = sk.group_id " + + * "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) " + * ); + * + * // Add month condition if month is provided + * if (month != null && !month.isEmpty()) { + * sql.append("AND MONTHNAME(a.indatetime) = ? "); + * } + * + * // Add year condition if year is provided + * if (year != null) { + * sql.append("AND YEAR(a.indatetime) = ? "); + * } + * + * sql. + * append("GROUP BY e.enrollment_id, e.name, YEAR(a.indatetime), MONTHNAME(a.indatetime), sd.salary_status, sk.group_id, sk.group_name" + * ); + * + * // Create a list of parameters to pass to the query + * List params = new ArrayList<>(); + * if (month != null && !month.isEmpty()) { + * params.add(month); + * } + * if (year != null) { + * params.add(year); + * } + * + * // Execute the query with the provided parameters + * List> results = jdbcTemplate.queryForList(sql.toString(), + * params.toArray()); + * return results; + * } + * + * public List> getSalaryReport(String month, int year, + * String salaryStatus,String loginId) { + * + * // Retrieve zone access for the user + * String ZoneWhare; + * String zoneAccessSQL = + * "SELECT zone FROM gcc_apps.login_mapping_user WHERE appuser_id = ?"; + * List> getAccess = + * jdbcTemplate.queryForList(zoneAccessSQL, loginId); + * System.out.println(zoneAccessSQL +"->"+ loginId); + * // Extract the zones from getAccess + * List zones = getAccess.stream() + * .map(access -> (String) access.get("zone")) + * .filter(Objects::nonNull) + * .collect(Collectors.toList()); + * + * // If the user has zone acc ess, add it to the WHERE clause + * if (!zones.isEmpty()) { + * String zoneList = zones.stream() + * .map(zone -> "'" + zone + "'") + * .collect(Collectors.joining(", ")); + * ZoneWhare = " AND e.zone IN ("+zoneList+")"; + * // System.out.println("AND e.zone IN ("+zoneList+")"); + * } + * else { + * ZoneWhare = " AND e.zone IN (0)"; + * } + * + * String sql = "SELECT " + + * "e.enrollment_id, " + + * "e.emp_id, " + + * "e.name, " + + * "e.incharge_name, " + // Fetch incharge_name from enrollment_table + * "e.incharge_designation, " + // Fetch incharge_designation from + * enrollment_table + * "YEAR(a.indatetime) AS year, " + + * "MONTHNAME(a.indatetime) AS month, " + // Use MONTHNAME to get month in words + * "COUNT(a.inby) AS total_days_present, " + + * "COUNT(a.leaveby) AS total_days_absent, " + // Changed to total_days_absent + * "COUNT(a.odby) AS total_days_od, " + + * "(COUNT(a.inby) + COUNT(a.odby)) AS total_days_salary, " + + * "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1) AS salary_per_day, " + * + // Fetch salary_per_day from staff_wages table + * "((COUNT(a.inby) + COUNT(a.odby)) * " + + * "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1)) AS total_salary, " + * + // Calculate total salary + * "sd.salary_status, " + + * "sk.group_id, " + // Fetch group_id from suyaudavi_kuzhu table + * "sk.group_name " + // Fetch group_name from suyaudavi_kuzhu table + * "FROM enrollment_table e " + + * "JOIN attendance a ON e.enrollment_id = a.enrollment_id " + + * "LEFT JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " + + * "AND YEAR(a.indatetime) = sd.year " + // Match year + * "AND MONTHNAME(a.indatetime) = sd.month " + // Match month name + * "LEFT JOIN suyaudavi_kuzhu sk ON e.group_id = sk.group_id " + // Join with + * suyaudavi_kuzhu table on group_id + * "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) " + * + // Removed unauthorizedleaveby + * "AND MONTHNAME(a.indatetime) = ? " + // Filter by month + * "AND YEAR(a.indatetime) = ? "+ // Filter by year + * "AND (sd.salary_status = 'Initiated' OR sd.salary_status = 'Approved') " + // + * Filter by year + * (salaryStatus != null && !salaryStatus.isEmpty() ? + * "AND sd.salary_status = ? " : "") + // Optional filter by salary status + * ZoneWhare + * +" GROUP BY e.enrollment_id, e.name, e.incharge_name, e.incharge_designation, YEAR(a.indatetime), MONTHNAME(a.indatetime), salary_per_day, sd.salary_status, sk.group_id, sk.group_name" + * ; // Group by new fields + * + * // Prepare the query parameters based on provided inputs + * List params = new ArrayList<>(); + * params.add(month); + * params.add(year); + * if (salaryStatus != null && !salaryStatus.isEmpty()) { + * params.add(salaryStatus); + * } + * + * // Execute the query with dynamic parameters + * List> results = jdbcTemplate.queryForList(sql, + * params.toArray()); + * return results; + * } + */ + + /* + * public List> getSalaryReport(String month, int year, + * String salaryStatus,String loginId) { + * + * // Retrieve zone access for the user + * String ZoneWhare; + * String zoneAccessSQL = + * "SELECT zone FROM gcc_apps.login_mapping_user WHERE appuser_id = ?"; + * List> getAccess = + * jdbcTemplate.queryForList(zoneAccessSQL, loginId); + * System.out.println(zoneAccessSQL +"->"+ loginId); + * // Extract the zones from getAccess + * List zones = getAccess.stream() + * .map(access -> (String) access.get("zone")) + * .filter(Objects::nonNull) + * .collect(Collectors.toList()); + * + * // If the user has zone acc ess, add it to the WHERE clause + * if (!zones.isEmpty()) { + * String zoneList = zones.stream() + * .map(zone -> "'" + zone + "'") + * .collect(Collectors.joining(", ")); + * ZoneWhare = " AND e.zone IN ("+zoneList+")"; + * // System.out.println("AND e.zone IN ("+zoneList+")"); + * } + * else { + * ZoneWhare = " AND e.zone IN (0)"; + * } + * + * String sql = "SELECT " + + * "e.enrollment_id, " + + * "e.emp_id, " + + * "e.name, " + + * "e.incharge_name, " + // Fetch incharge_name from enrollment_table + * "e.incharge_designation, " + // Fetch incharge_designation from + * enrollment_table + * "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS iyear, " + + * "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS imonth, " + * + // Use MONTHNAME to get month in words + * "COUNT(DISTINCT DATE(a.indatetime)) AS total_days_present, " + + * "COUNT(DISTINCT DATE(a.leavedatetime)) AS total_days_absent, " + // Changed + * to total_days_absent + * "COUNT(DISTINCT DATE(a.oddatetime)) AS total_days_od, " + + * "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) AS total_days_salary, " + * + + * "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1) AS salary_per_day, " + * + // Fetch salary_per_day from staff_wages table + * "((COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) * " + * + + * "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1)) AS total_salary, " + * + // Calculate total salary + * "sd.salary_status, " + + * "sk.group_id, " + // Fetch group_id from suyaudavi_kuzhu table + * "sk.group_name " + // Fetch group_name from suyaudavi_kuzhu table + * "FROM enrollment_table e " + + * "JOIN attendance a ON e.enrollment_id = a.enrollment_id " + + * "LEFT JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " + + * "AND YEAR(a.indatetime) = sd.year " + // Match year + * "AND MONTHNAME(a.indatetime) = sd.month " + // Match month name + * "LEFT JOIN suyaudavi_kuzhu sk ON e.group_id = sk.group_id " + // Join with + * suyaudavi_kuzhu table on group_id + * "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) " + * + // Removed unauthorizedleaveby + * "AND MONTHNAME(a.indatetime) = ? " + // Filter by month + * "AND YEAR(a.indatetime) = ? "+ // Filter by year + * "AND (sd.salary_status = 'Initiated' OR sd.salary_status = 'Approved') " + // + * Filter by year + * (salaryStatus != null && !salaryStatus.isEmpty() ? + * "AND sd.salary_status = ? " : "") + // Optional filter by salary status + * ZoneWhare + * +" GROUP BY e.enrollment_id, e.name, e.incharge_name, e.incharge_designation, iyear, imonth, salary_per_day, sd.salary_status, sk.group_id, sk.group_name" + * ; // Group by new fields + * + * // Prepare the query parameters based on provided inputs + * List params = new ArrayList<>(); + * params.add(month); + * params.add(year); + * if (salaryStatus != null && !salaryStatus.isEmpty()) { + * params.add(salaryStatus); + * } + * + * // Execute the query with dynamic parameters + * List> results = jdbcTemplate.queryForList(sql, + * params.toArray()); + * return results; + * } + */ + public List> getSalaryReport(String month, Integer year, String salaryStatus, String groupName, + String loginId) { // Retrieve zone access for the user - String ZoneWhare=""; + String ZoneWhare = ""; String zoneAccessSQL = "SELECT zone FROM gcc_apps.login_mapping_user WHERE appuser_id = ?"; List> getAccess = jdbcTemplate.queryForList(zoneAccessSQL, loginId); - System.out.println(zoneAccessSQL +"->"+ loginId); + System.out.println(zoneAccessSQL + "->" + loginId); /* - // Extract the zones from getAccess - List zones = getAccess.stream() - .map(access -> (String) access.get("zone")) - .filter(Objects::nonNull) - .collect(Collectors.toList()); -*/ + * // Extract the zones from getAccess + * List zones = getAccess.stream() + * .map(access -> (String) access.get("zone")) + * .filter(Objects::nonNull) + * .collect(Collectors.toList()); + */ // Extract the zones from getAccess List zones = new ArrayList(); if (getAccess != null) { - for (Map access : getAccess) { - Object zoneObj = access.get("zone"); - if (zoneObj != null) { - zones.add(zoneObj.toString()); - } - } - } -/* - // If the user has zone access, add it to the WHERE clause - if (!zones.isEmpty()) { - String zoneList = zones.stream() - .map(zone -> "'" + zone + "'") - .collect(Collectors.joining(", ")); - ZoneWhare = " AND en.zone IN ("+zoneList+")"; + for (Map access : getAccess) { + Object zoneObj = access.get("zone"); + if (zoneObj != null) { + zones.add(zoneObj.toString()); + } + } } - else { - ZoneWhare = " AND en.zone IN (0)"; - } -*/ + /* + * // If the user has zone access, add it to the WHERE clause + * if (!zones.isEmpty()) { + * String zoneList = zones.stream() + * .map(zone -> "'" + zone + "'") + * .collect(Collectors.joining(", ")); + * ZoneWhare = " AND en.zone IN ("+zoneList+")"; + * } + * else { + * ZoneWhare = " AND en.zone IN (0)"; + * } + */ // If the user has zone access, add it to the WHERE clause - //String ZoneWhare = ""; + // String ZoneWhare = ""; if (zones != null && !zones.isEmpty()) { - StringBuilder zoneListBuilder = new StringBuilder(); - for (int i = 0; i < zones.size(); i++) { - zoneListBuilder.append("'").append(zones.get(i)).append("'"); - if (i < zones.size() - 1) { - zoneListBuilder.append(", "); - } - } - ZoneWhare = " AND en.zone IN (" + zoneListBuilder.toString() + ")"; + StringBuilder zoneListBuilder = new StringBuilder(); + for (int i = 0; i < zones.size(); i++) { + zoneListBuilder.append("'").append(zones.get(i)).append("'"); + if (i < zones.size() - 1) { + zoneListBuilder.append(", "); + } + } + ZoneWhare = " AND en.zone IN (" + zoneListBuilder.toString() + ")"; } else { - ZoneWhare = " AND en.zone IN (0)"; + ZoneWhare = " AND en.zone IN (0)"; } - + String sql = "select en.emp_id, en.name, en.incharge_name, en.designation, en.incharge_designation, sk.group_name, s.total_days_present, s.total_days_od, " + "s.total_days_absent, s.total_days_salary, s.month as imonth,s.year as iyear, s.salary_status, s.salary_amount as total_salary, " + "DAY(LAST_DAY(STR_TO_DATE(CONCAT(s.year, '-', s.month, '-01'), '%Y-%M-%d'))) AS total_days from salary_details s " @@ -825,1178 +887,1373 @@ public class NulmService { List> results = jdbcTemplate.queryForList(sql.toString(), params.toArray()); return results; } - /* - public List> getSalaryReport(String month, Integer year, String salaryStatus, String groupName) { - String sql = "select en.emp_id, en.name, en.incharge_name, en.incharge_designation, sk.group_name, s.total_days_present, s.total_days_od, " - + "s.total_days_absent, s.total_days_salary, s.month as imonth,s.year as iyear, s.salary_status, s.salary_amount as total_salary, " - + "DAY(LAST_DAY(STR_TO_DATE(CONCAT(s.year, '-', s.month, '-01'), '%Y-%M-%d'))) AS total_days from salary_details s " - + "left join enrollment_table en on s.enrollment_id = en.enrollment_id " - + "left join suyaudavi_kuzhu sk on s.group_id = sk.group_id " - + "where s.month = ? and s.year =? " - + "AND (s.salary_status = 'Initiated' OR s.salary_status = 'Approved') " - + (salaryStatus != null && !salaryStatus.isEmpty() ? "AND s.salary_status = ? " : "") - + (groupName != null && !groupName.isEmpty() ? "AND sk.group_name = ? " : ""); - - // Prepare the query parameters based on provided inputs - List params = new ArrayList<>(); - params.add(month); - params.add(year); - if (salaryStatus != null && !salaryStatus.isEmpty()) { - params.add(salaryStatus); - } - if (groupName != null && !groupName.isEmpty()) { - params.add(groupName); - } - - List> results = jdbcTemplate.queryForList(sql.toString(), params.toArray()); - return results; -} -*/ - /* - public List> getSalaryReport(String month, int year, String salaryStatus ,String groupName, String loginId) { - // Retrieve zone access for the user - String ZoneWhere; - String zoneAccessSQL = "SELECT zone FROM gcc_apps.login_mapping_user WHERE appuser_id = ?"; - List> getAccess = jdbcTemplate.queryForList(zoneAccessSQL, loginId); - System.out.println(zoneAccessSQL +"->"+ loginId); - // Extract the zones from getAccess - List zones = getAccess.stream() - .map(access -> (String) access.get("zone")) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - - // If the user has zone acc ess, add it to the WHERE clause - if (!zones.isEmpty()) { - String zoneList = zones.stream() - .map(zone -> "'" + zone + "'") - .collect(Collectors.joining(", ")); - ZoneWhere = " AND e.zone IN ("+zoneList+")"; - // System.out.println("AND e.zone IN ("+zoneList+")"); - } - else { - ZoneWhere = " AND e.zone IN (0)"; - } - - String sql = "SELECT " + - "e.enrollment_id, " + - "e.emp_id, " + - "e.name, " + - "e.incharge_name, " + // Fetch incharge_name from enrollment_table - "e.incharge_designation, " + // Fetch incharge_designation from enrollment_table - "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS iyear, " + - "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS imonth, " + // Use MONTHNAME to get month in words - "COUNT(DISTINCT DATE(a.indatetime)) AS total_days_present, " + - "COUNT(DISTINCT DATE(a.oddatetime)) AS total_days_od, " + // Count of OD days - "MAX(DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)))) AS total_days, " + // Calculate total days in the month - "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) AS total_days_salary, " + // Calculate total present and OD days - "(MAX(DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)))) - " + // Calculate total days absent - "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime)))) AS total_days_absent, " + // Calculate total days absent - "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1) AS salary_per_day, " + // Fetch salary_per_day from staff_wages table - "((COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) * " + - "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1)) AS total_salary, " + // Calculate total salary - "sd.salary_status, " + - "sk.group_id, " + // Fetch group_id from suyaudavi_kuzhu table - "sk.group_name " + // Fetch group_name from suyaudavi_kuzhu table - "FROM enrollment_table e " + - "JOIN attendance a ON e.enrollment_id = a.enrollment_id " + - "LEFT JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " + - "AND YEAR(a.indatetime) = sd.year " + // Match year - "AND MONTHNAME(a.indatetime) = sd.month " + // Match month name - "LEFT JOIN suyaudavi_kuzhu sk ON e.group_id = sk.group_id " + // Join with suyaudavi_kuzhu table on group_id - "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) " + // Removed unauthorizedleaveby - "AND MONTHNAME(a.indatetime) = ? " + // Filter by month - "AND YEAR(a.indatetime) = ? " + // Filter by year - "AND (sd.salary_status = 'Initiated' OR sd.salary_status = 'Approved') " + // Filter by salary status - (salaryStatus != null && !salaryStatus.isEmpty() ? "AND sd.salary_status = ? " : "") + - (groupName != null && !groupName.isEmpty() ? "AND sk.group_name = ? " : "")+// Optional filter by salary status - ZoneWhere +" GROUP BY e.enrollment_id, e.name, e.incharge_name, e.incharge_designation, iyear, imonth, salary_per_day, sd.salary_status, sk.group_id, sk.group_name"; // Group by new fields - - // Prepare the query parameters based on provided inputs - List params = new ArrayList<>(); - params.add(month); - params.add(year); - if (salaryStatus != null && !salaryStatus.isEmpty()) { - params.add(salaryStatus); - } - if (groupName != null && !groupName.isEmpty()) { - params.add(groupName); - } - - // Execute the query with dynamic parameters - List> results = jdbcTemplate.queryForList(sql, params.toArray()); - return results; - } - */ - - /* - public List> getAttendanceWithInitiatedSalary(String inchargeName, String month) { - String sql = "SELECT " + - "e.enrollment_id, " + - "e.emp_id, " + - "e.name, " + - "YEAR(a.indatetime) AS year, " + - "MONTHNAME(a.indatetime) AS month, " + // Get month in words - "COUNT(a.inby) AS total_days_present, " + - "COUNT(a.leaveby) AS total_days_absent, " + // Changed to total_days_absent - "COUNT(a.odby) AS total_days_od, " + - "(COUNT(a.inby) + COUNT(a.odby)) AS total_days_salary, " + - "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1) AS salary_per_day, " + // Fetch salary_per_day from staff_wages table - "((COUNT(a.inby) + COUNT(a.odby)) * " + - "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1)) AS total_salary, " + // Calculate total salary - "sd.salary_status " + - "FROM enrollment_table e " + - "JOIN attendance a ON e.enrollment_id = a.enrollment_id " + // Join with attendance table - "LEFT JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " + // Left join with salary_details - "AND YEAR(a.indatetime) = sd.year " + // Match year - "AND MONTHNAME(a.indatetime) = sd.month " + // Match month name - "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) " + // Removed unauthorizedleaveby - "AND e.incharge_name = ? " + // Filter by incharge_name - "AND MONTHNAME(a.indatetime) = ? " + // Filter by month - "AND sd.salary_status IN ('Initiated', 'Approved') " + // Filter by salary status 'Initiated' or 'Approved' - "GROUP BY e.enrollment_id, e.name, YEAR(a.indatetime), MONTHNAME(a.indatetime), salary_per_day, sd.salary_status"; // Group by required fields - - List> results = jdbcTemplate.queryForList(sql, inchargeName, month); - return results; - } - */ - /* - public List> getAttendanceWithInitiatedSalary(String inchargeName, String month) { - String sql = "SELECT " + - "e.enrollment_id, " + - "e.emp_id, " + - "e.name, " + - "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS year, " + - "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS month, " + - "COUNT(DISTINCT DATE(a.indatetime)) AS total_days_present, " + - "COUNT(DISTINCT DATE(a.leavedatetime)) AS total_days_absent, " + - "COUNT(DISTINCT DATE(a.oddatetime)) AS total_days_od, " + - "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) AS total_days_salary, " + - "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1) AS salary_per_day, " + - "((COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) * " + - "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1)) AS total_salary, " + - "sd.salary_status " + - "FROM enrollment_table e " + - "JOIN attendance a ON e.enrollment_id = a.enrollment_id " + - "LEFT JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " + - "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) " + - "AND e.incharge_name = ? " + - "AND sd.salary_status IN ('Initiated', 'Approved') " + - "AND (MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = ? OR ? IS NULL) " + // Ensure month matches - "GROUP BY e.enrollment_id, e.emp_id, e.name, " + - "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + // Grouping by COALESCE year - "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), sd.salary_status"; // Grouping by COALESCE month - - List> results = jdbcTemplate.queryForList(sql, inchargeName, month, month); - return results; - } - */ - /* - public List> getAttendanceWithInitiatedSalary(String inchargeId, String month) { - String sql = "SELECT " + - "e.enrollment_id, " + - "e.emp_id, " + - "e.name, " + - "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS year, " + - "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS month, " + - "COUNT(DISTINCT DATE(a.indatetime)) AS total_days_present, " + - "COUNT(DISTINCT DATE(a.oddatetime)) AS total_days_od, " + - "MAX(DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)))) AS total_days, " + // Total days in the month - "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) AS total_days_salary, " + - "(MAX(DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)))) - " + // Total days in the month - "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime)))) AS total_days_absent, " + // Calculate total days absent - "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1) AS salary_per_day, " + - "((COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) * " + - "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1)) AS total_salary, " + - "sd.salary_status " + - "FROM enrollment_table e " + - "JOIN attendance a ON e.enrollment_id = a.enrollment_id " + - "LEFT JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " + - "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) " + - "AND e.incharge_id = ? " + - "AND sd.salary_status IN ('Initiated', 'Approved') " + - "AND sd.month = ? " + // Filtering based on salary_details month - "AND MONTHNAME(a.indatetime) = ? " + // Additional filtering on attendance - "GROUP BY e.enrollment_id, e.emp_id, e.name, " + - "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + - "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), sd.salary_status"; - - List> results = jdbcTemplate.queryForList(sql, inchargeId, month, month); - return results; - } - */ - /* - public List> getAttendanceWithInitiatedSalary(String inchargeId, String month, String inchargeName, Integer zone) { - StringBuilder sql = new StringBuilder("SELECT " + - "e.group_id, " + - "(SELECT group_name FROM suyaudavi_kuzhu WHERE suyaudavi_kuzhu.group_id = e.group_id LIMIT 1) AS group_name, " + - "a.enrollment_id, " + - "e.emp_id, " + - "e.name, " + - "e.incharge_id, " + - "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1) AS salary_per_day, " + - "(SELECT wage_id FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1) AS wage_id, " + - "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS year, " + - "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS month, " + - "DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime))) AS total_days, " + - "COUNT(DISTINCT DATE(a.indatetime)) AS total_days_present, " + - "COUNT(DISTINCT DATE(a.oddatetime)) AS total_days_od, " + - "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) AS total_days_salary, " + - "((COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) * " + - "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1)) AS total_salary, " + - "(MAX(DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)))) - " + - "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime)))) AS total_days_absent, " + - "IFNULL(s.salary_status, '') AS salary_status " + - "FROM attendance AS a " + - "INNER JOIN enrollment_table AS e ON a.enrollment_id = e.enrollment_id " + - "LEFT JOIN salary_details AS s ON a.enrollment_id = s.enrollment_id " + - "AND s.month = MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) " + - "AND s.year = YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) " + - "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) "); - - // Append condition for incharge_id - sql.append("AND (? IS NULL OR e.incharge_id = ?) "); - - // Append condition for incharge_name - sql.append("AND (? IS NULL OR e.incharge_name = ?) "); - - // Append condition for zone - sql.append("AND (? IS NULL OR e.zone = ?) "); - - // Append condition for month if provided - if (month != null && !month.isEmpty()) { - sql.append("AND MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = ? "); - } - - // Add condition to filter by salary_status (only 'Initiated' or 'Approved') - sql.append("AND IFNULL(s.salary_status, '') IN ('Initiated', 'Approved') "); - - // Group by necessary columns - sql.append("GROUP BY a.enrollment_id, e.group_id, " + - "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + - "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + - "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1), " + - "(SELECT wage_id FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1), " + - "(SELECT group_name FROM suyaudavi_kuzhu WHERE suyaudavi_kuzhu.group_id = e.group_id LIMIT 1), " + - "DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime))), " + - "s.salary_status"); - - // Create a list of parameters - List params = new ArrayList<>(); - params.add(inchargeId); - params.add(inchargeId); - params.add(inchargeName); - params.add(inchargeName); - params.add(zone); - params.add(zone); // Added twice for the conditional check in the SQL - if (month != null && !month.isEmpty()) { - params.add(month); - } - - // Log the SQL and parameters (optional for debugging) - System.out.println("Generated SQL: " + sql.toString()); - System.out.println("Parameters: " + params); - - // Execute the query using JdbcTemplate - List> results = jdbcTemplate.queryForList(sql.toString(), params.toArray()); - return results; - } - - */ - /* - public List> getAttendanceWithInitiatedSalary(String inchargeId, String month, String inchargeName, int zone) { - StringBuilder sql = new StringBuilder("SELECT " + - "e.group_id, " + - "(SELECT group_name FROM suyaudavi_kuzhu WHERE suyaudavi_kuzhu.group_id = e.group_id LIMIT 1) AS group_name, " + - "a.enrollment_id, " + - "e.emp_id, " + - "e.name, " + - "e.incharge_id, " + - "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1) AS salary_per_day, " + - "(SELECT wage_id FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1) AS wage_id, " + - "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS year, " + - "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS month, " + - "DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime))) AS total_days, " + - "COUNT(DISTINCT DATE(a.indatetime)) AS total_days_present, " + - "COUNT(DISTINCT CASE WHEN a.indatetime IS NULL THEN DATE(a.oddatetime) END) AS total_days_od, " + - "COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT CASE WHEN a.indatetime IS NULL THEN DATE(a.oddatetime) END) AS total_days_salary, " + - "((COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT CASE WHEN a.indatetime IS NULL THEN DATE(a.oddatetime) END)) * " + - "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1)) AS total_salary, " + - "(MAX(DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)))) - " + - "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT CASE WHEN a.indatetime IS NULL THEN DATE(a.oddatetime) END))) AS total_days_absent, " + - "IFNULL(s.salary_status, '') AS salary_status " + - "FROM attendance AS a " + - "INNER JOIN enrollment_table AS e ON a.enrollment_id = e.enrollment_id " + - "LEFT JOIN salary_details AS s ON a.enrollment_id = s.enrollment_id " + - "AND s.month = MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) " + - "AND s.year = YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) " + - "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) "); - - // Append condition for incharge_id - sql.append("AND (? IS NULL OR e.incharge_id = ?) "); - - // Append condition for incharge_name - sql.append("AND (? IS NULL OR e.incharge_name = ?) "); - - // Append condition for month if provided - if (month != null && !month.isEmpty()) { - sql.append("AND MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = ? "); - } - - // Add condition to filter by salary_status (only 'Initiated' or 'Approved') - sql.append("AND IFNULL(s.salary_status, '') IN ('Initiated', 'Approved') "); - - // Group by necessary columns - sql.append("GROUP BY a.enrollment_id, e.group_id, " + - "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + - "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + - "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1), " + - "(SELECT wage_id FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1), " + - "(SELECT group_name FROM suyaudavi_kuzhu WHERE suyaudavi_kuzhu.group_id = e.group_id LIMIT 1), " + - "DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime))), " + - "s.salary_status"); - - // Create a list of parameters - List params = new ArrayList<>(); - params.add(inchargeId); - params.add(inchargeId); // Added twice for the conditional check in the SQL - params.add(inchargeName); - params.add(inchargeName); // Added twice for the conditional check in the SQL - if (month != null && !month.isEmpty()) { - params.add(month); - } - - // Log the SQL and parameters (optional for debugging) - System.out.println("Generated SQL: " + sql.toString()); - System.out.println("Parameters: " + params); - - // Execute the query using JdbcTemplate - List> results = jdbcTemplate.queryForList(sql.toString(), params.toArray()); - return results; - } - */ - - public List> getAttendanceWithInitiatedSalary( - int inchargeId, String month, String year, String inchargeName, List enrollmentIds) { - - String sql = "SELECT " + - "e.group_id, " + - "(SELECT group_name FROM suyaudavi_kuzhu WHERE suyaudavi_kuzhu.group_id = e.group_id LIMIT 1) AS group_name, " + - "a.enrollment_id, e.emp_id, e.name, e.incharge_id, " + - "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1) AS salary_per_day, " + - "(SELECT wage_id FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1) AS wage_id, " + - "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS year, " + - "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS month, " + - "DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime))) AS total_days, " + - "COUNT(DISTINCT DATE(a.indatetime)) AS total_days_present, " + - "COUNT(DISTINCT CASE WHEN a.indatetime IS NULL THEN DATE(a.oddatetime) END) AS total_days_od, " + - "COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT CASE WHEN a.indatetime IS NULL THEN DATE(a.oddatetime) END) AS total_days_salary, " + - "((COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT CASE WHEN a.indatetime IS NULL THEN DATE(a.oddatetime) END)) * " + - "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1)) AS total_salary, " + - "(MAX(DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)))) - " + - "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT CASE WHEN a.indatetime IS NULL THEN DATE(a.oddatetime) END))) AS total_days_absent, " + - "IFNULL(s.salary_status, '') AS salary_status " + - "FROM attendance AS a " + - "INNER JOIN enrollment_table AS e ON a.enrollment_id = e.enrollment_id " + - "LEFT JOIN salary_details AS s ON a.enrollment_id = s.enrollment_id " + - "AND s.month = MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) " + - "AND s.year = YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) " + - "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) " + - "AND (? IS NULL OR e.incharge_id = ?) " + - "AND (? IS NULL OR e.incharge_name = ?) "; - - if (month != null && !month.isEmpty()) { - sql += "AND MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = ? "; - } - if (year != null && !year.isEmpty()) { - sql += "AND YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = ? "; - } - - - // Assuming enrollmentIds is a List or List - StringBuilder placeholders = new StringBuilder(); - for (int i = 0; i < enrollmentIds.size(); i++) { - placeholders.append("?"); - if (i < enrollmentIds.size() - 1) { - placeholders.append(", "); - } - } - String inClause = placeholders.toString() + ") "; - - sql += "AND IFNULL(s.salary_status, '') IN ('Initiated', 'Approved') " + - "AND e.enrollment_id IN (" + - inClause + - "GROUP BY a.enrollment_id, e.group_id, " + - "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + - "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + - "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1), " + - "(SELECT wage_id FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1), " + - "(SELECT group_name FROM suyaudavi_kuzhu WHERE suyaudavi_kuzhu.group_id = e.group_id LIMIT 1), " + - "DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime))), " + - "s.salary_status"; - - List params = new ArrayList<>(); - params.add(inchargeId); - params.add(inchargeId); - params.add(inchargeName); - params.add(inchargeName); - - - if (month != null && !month.isEmpty()) { - params.add(month); - } - if (year != null && !year.isEmpty()) { - params.add(year); - } - - params.addAll(enrollmentIds); - - System.out.println("SQL = " + sql); - System.out.println("Parameter = "+ params); - - return jdbcTemplate.queryForList(sql, params.toArray()); + /* + * public List> getSalaryReport(String month, Integer year, + * String salaryStatus, String groupName) { + * String sql = + * "select en.emp_id, en.name, en.incharge_name, en.incharge_designation, sk.group_name, s.total_days_present, s.total_days_od, " + * + + * "s.total_days_absent, s.total_days_salary, s.month as imonth,s.year as iyear, s.salary_status, s.salary_amount as total_salary, " + * + + * "DAY(LAST_DAY(STR_TO_DATE(CONCAT(s.year, '-', s.month, '-01'), '%Y-%M-%d'))) AS total_days from salary_details s " + * + "left join enrollment_table en on s.enrollment_id = en.enrollment_id " + * + "left join suyaudavi_kuzhu sk on s.group_id = sk.group_id " + * + "where s.month = ? and s.year =? " + * + "AND (s.salary_status = 'Initiated' OR s.salary_status = 'Approved') " + * + (salaryStatus != null && !salaryStatus.isEmpty() ? + * "AND s.salary_status = ? " : "") + * + (groupName != null && !groupName.isEmpty() ? "AND sk.group_name = ? " : + * ""); + * + * // Prepare the query parameters based on provided inputs + * List params = new ArrayList<>(); + * params.add(month); + * params.add(year); + * if (salaryStatus != null && !salaryStatus.isEmpty()) { + * params.add(salaryStatus); + * } + * if (groupName != null && !groupName.isEmpty()) { + * params.add(groupName); + * } + * + * List> results = jdbcTemplate.queryForList(sql.toString(), + * params.toArray()); + * return results; + * } + */ + /* + * public List> getSalaryReport(String month, int year, + * String salaryStatus ,String groupName, String loginId) { + * // Retrieve zone access for the user + * String ZoneWhere; + * String zoneAccessSQL = + * "SELECT zone FROM gcc_apps.login_mapping_user WHERE appuser_id = ?"; + * List> getAccess = + * jdbcTemplate.queryForList(zoneAccessSQL, loginId); + * System.out.println(zoneAccessSQL +"->"+ loginId); + * // Extract the zones from getAccess + * List zones = getAccess.stream() + * .map(access -> (String) access.get("zone")) + * .filter(Objects::nonNull) + * .collect(Collectors.toList()); + * + * // If the user has zone acc ess, add it to the WHERE clause + * if (!zones.isEmpty()) { + * String zoneList = zones.stream() + * .map(zone -> "'" + zone + "'") + * .collect(Collectors.joining(", ")); + * ZoneWhere = " AND e.zone IN ("+zoneList+")"; + * // System.out.println("AND e.zone IN ("+zoneList+")"); + * } + * else { + * ZoneWhere = " AND e.zone IN (0)"; + * } + * + * String sql = "SELECT " + + * "e.enrollment_id, " + + * "e.emp_id, " + + * "e.name, " + + * "e.incharge_name, " + // Fetch incharge_name from enrollment_table + * "e.incharge_designation, " + // Fetch incharge_designation from + * enrollment_table + * "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS iyear, " + + * "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS imonth, " + * + // Use MONTHNAME to get month in words + * "COUNT(DISTINCT DATE(a.indatetime)) AS total_days_present, " + + * "COUNT(DISTINCT DATE(a.oddatetime)) AS total_days_od, " + // Count of OD days + * "MAX(DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)))) AS total_days, " + * + // Calculate total days in the month + * "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) AS total_days_salary, " + * + // Calculate total present and OD days + * "(MAX(DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)))) - " + * + // Calculate total days absent + * "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime)))) AS total_days_absent, " + * + // Calculate total days absent + * "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1) AS salary_per_day, " + * + // Fetch salary_per_day from staff_wages table + * "((COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) * " + * + + * "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1)) AS total_salary, " + * + // Calculate total salary + * "sd.salary_status, " + + * "sk.group_id, " + // Fetch group_id from suyaudavi_kuzhu table + * "sk.group_name " + // Fetch group_name from suyaudavi_kuzhu table + * "FROM enrollment_table e " + + * "JOIN attendance a ON e.enrollment_id = a.enrollment_id " + + * "LEFT JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " + + * "AND YEAR(a.indatetime) = sd.year " + // Match year + * "AND MONTHNAME(a.indatetime) = sd.month " + // Match month name + * "LEFT JOIN suyaudavi_kuzhu sk ON e.group_id = sk.group_id " + // Join with + * suyaudavi_kuzhu table on group_id + * "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) " + * + // Removed unauthorizedleaveby + * "AND MONTHNAME(a.indatetime) = ? " + // Filter by month + * "AND YEAR(a.indatetime) = ? " + // Filter by year + * "AND (sd.salary_status = 'Initiated' OR sd.salary_status = 'Approved') " + // + * Filter by salary status + * (salaryStatus != null && !salaryStatus.isEmpty() ? + * "AND sd.salary_status = ? " : "") + + * (groupName != null && !groupName.isEmpty() ? "AND sk.group_name = ? " : + * "")+// Optional filter by salary status + * ZoneWhere + * +" GROUP BY e.enrollment_id, e.name, e.incharge_name, e.incharge_designation, iyear, imonth, salary_per_day, sd.salary_status, sk.group_id, sk.group_name" + * ; // Group by new fields + * + * // Prepare the query parameters based on provided inputs + * List params = new ArrayList<>(); + * params.add(month); + * params.add(year); + * if (salaryStatus != null && !salaryStatus.isEmpty()) { + * params.add(salaryStatus); + * } + * if (groupName != null && !groupName.isEmpty()) { + * params.add(groupName); + * } + * + * // Execute the query with dynamic parameters + * List> results = jdbcTemplate.queryForList(sql, + * params.toArray()); + * return results; + * } + */ + + /* + * public List> getAttendanceWithInitiatedSalary(String + * inchargeName, String month) { + * String sql = "SELECT " + + * "e.enrollment_id, " + + * "e.emp_id, " + + * "e.name, " + + * "YEAR(a.indatetime) AS year, " + + * "MONTHNAME(a.indatetime) AS month, " + // Get month in words + * "COUNT(a.inby) AS total_days_present, " + + * "COUNT(a.leaveby) AS total_days_absent, " + // Changed to total_days_absent + * "COUNT(a.odby) AS total_days_od, " + + * "(COUNT(a.inby) + COUNT(a.odby)) AS total_days_salary, " + + * "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1) AS salary_per_day, " + * + // Fetch salary_per_day from staff_wages table + * "((COUNT(a.inby) + COUNT(a.odby)) * " + + * "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1)) AS total_salary, " + * + // Calculate total salary + * "sd.salary_status " + + * "FROM enrollment_table e " + + * "JOIN attendance a ON e.enrollment_id = a.enrollment_id " + // Join with + * attendance table + * "LEFT JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " + // + * Left join with salary_details + * "AND YEAR(a.indatetime) = sd.year " + // Match year + * "AND MONTHNAME(a.indatetime) = sd.month " + // Match month name + * "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) " + * + // Removed unauthorizedleaveby + * "AND e.incharge_name = ? " + // Filter by incharge_name + * "AND MONTHNAME(a.indatetime) = ? " + // Filter by month + * "AND sd.salary_status IN ('Initiated', 'Approved') " + // Filter by salary + * status 'Initiated' or 'Approved' + * "GROUP BY e.enrollment_id, e.name, YEAR(a.indatetime), MONTHNAME(a.indatetime), salary_per_day, sd.salary_status" + * ; // Group by required fields + * + * List> results = jdbcTemplate.queryForList(sql, + * inchargeName, month); + * return results; + * } + */ + /* + * public List> getAttendanceWithInitiatedSalary(String + * inchargeName, String month) { + * String sql = "SELECT " + + * "e.enrollment_id, " + + * "e.emp_id, " + + * "e.name, " + + * "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS year, " + + * "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS month, " + * + + * "COUNT(DISTINCT DATE(a.indatetime)) AS total_days_present, " + + * "COUNT(DISTINCT DATE(a.leavedatetime)) AS total_days_absent, " + + * "COUNT(DISTINCT DATE(a.oddatetime)) AS total_days_od, " + + * "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) AS total_days_salary, " + * + + * "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1) AS salary_per_day, " + * + + * "((COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) * " + * + + * "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1)) AS total_salary, " + * + + * "sd.salary_status " + + * "FROM enrollment_table e " + + * "JOIN attendance a ON e.enrollment_id = a.enrollment_id " + + * "LEFT JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " + + * "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) " + * + + * "AND e.incharge_name = ? " + + * "AND sd.salary_status IN ('Initiated', 'Approved') " + + * "AND (MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = ? OR ? IS NULL) " + * + // Ensure month matches + * "GROUP BY e.enrollment_id, e.emp_id, e.name, " + + * "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + // Grouping + * by COALESCE year + * "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), sd.salary_status" + * ; // Grouping by COALESCE month + * + * List> results = jdbcTemplate.queryForList(sql, + * inchargeName, month, month); + * return results; + * } + */ + /* + * public List> getAttendanceWithInitiatedSalary(String + * inchargeId, String month) { + * String sql = "SELECT " + + * "e.enrollment_id, " + + * "e.emp_id, " + + * "e.name, " + + * "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS year, " + + * "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS month, " + * + + * "COUNT(DISTINCT DATE(a.indatetime)) AS total_days_present, " + + * "COUNT(DISTINCT DATE(a.oddatetime)) AS total_days_od, " + + * "MAX(DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)))) AS total_days, " + * + // Total days in the month + * "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) AS total_days_salary, " + * + + * "(MAX(DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)))) - " + * + // Total days in the month + * "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime)))) AS total_days_absent, " + * + // Calculate total days absent + * "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1) AS salary_per_day, " + * + + * "((COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) * " + * + + * "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1)) AS total_salary, " + * + + * "sd.salary_status " + + * "FROM enrollment_table e " + + * "JOIN attendance a ON e.enrollment_id = a.enrollment_id " + + * "LEFT JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " + + * "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) " + * + + * "AND e.incharge_id = ? " + + * "AND sd.salary_status IN ('Initiated', 'Approved') " + + * "AND sd.month = ? " + // Filtering based on salary_details month + * "AND MONTHNAME(a.indatetime) = ? " + // Additional filtering on attendance + * "GROUP BY e.enrollment_id, e.emp_id, e.name, " + + * "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + + * "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), sd.salary_status" + * ; + * + * List> results = jdbcTemplate.queryForList(sql, + * inchargeId, month, month); + * return results; + * } + */ + /* + * public List> getAttendanceWithInitiatedSalary(String + * inchargeId, String month, String inchargeName, Integer zone) { + * StringBuilder sql = new StringBuilder("SELECT " + + * "e.group_id, " + + * "(SELECT group_name FROM suyaudavi_kuzhu WHERE suyaudavi_kuzhu.group_id = e.group_id LIMIT 1) AS group_name, " + * + + * "a.enrollment_id, " + + * "e.emp_id, " + + * "e.name, " + + * "e.incharge_id, " + + * "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1) AS salary_per_day, " + * + + * "(SELECT wage_id FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1) AS wage_id, " + * + + * "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS year, " + + * "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS month, " + * + + * "DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime))) AS total_days, " + * + + * "COUNT(DISTINCT DATE(a.indatetime)) AS total_days_present, " + + * "COUNT(DISTINCT DATE(a.oddatetime)) AS total_days_od, " + + * "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) AS total_days_salary, " + * + + * "((COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) * " + * + + * "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1)) AS total_salary, " + * + + * "(MAX(DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)))) - " + * + + * "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime)))) AS total_days_absent, " + * + + * "IFNULL(s.salary_status, '') AS salary_status " + + * "FROM attendance AS a " + + * "INNER JOIN enrollment_table AS e ON a.enrollment_id = e.enrollment_id " + + * "LEFT JOIN salary_details AS s ON a.enrollment_id = s.enrollment_id " + + * "AND s.month = MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) " + * + + * "AND s.year = YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) " + + * "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) " + * ); + * + * // Append condition for incharge_id + * sql.append("AND (? IS NULL OR e.incharge_id = ?) "); + * + * // Append condition for incharge_name + * sql.append("AND (? IS NULL OR e.incharge_name = ?) "); + * + * // Append condition for zone + * sql.append("AND (? IS NULL OR e.zone = ?) "); + * + * // Append condition for month if provided + * if (month != null && !month.isEmpty()) { + * sql. + * append("AND MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = ? " + * ); + * } + * + * // Add condition to filter by salary_status (only 'Initiated' or 'Approved') + * sql.append("AND IFNULL(s.salary_status, '') IN ('Initiated', 'Approved') "); + * + * // Group by necessary columns + * sql.append("GROUP BY a.enrollment_id, e.group_id, " + + * "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + + * "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + + * "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1), " + * + + * "(SELECT wage_id FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1), " + * + + * "(SELECT group_name FROM suyaudavi_kuzhu WHERE suyaudavi_kuzhu.group_id = e.group_id LIMIT 1), " + * + + * "DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime))), " + + * "s.salary_status"); + * + * // Create a list of parameters + * List params = new ArrayList<>(); + * params.add(inchargeId); + * params.add(inchargeId); + * params.add(inchargeName); + * params.add(inchargeName); + * params.add(zone); + * params.add(zone); // Added twice for the conditional check in the SQL + * if (month != null && !month.isEmpty()) { + * params.add(month); + * } + * + * // Log the SQL and parameters (optional for debugging) + * System.out.println("Generated SQL: " + sql.toString()); + * System.out.println("Parameters: " + params); + * + * // Execute the query using JdbcTemplate + * List> results = jdbcTemplate.queryForList(sql.toString(), + * params.toArray()); + * return results; + * } + * + */ + /* + * public List> getAttendanceWithInitiatedSalary(String + * inchargeId, String month, String inchargeName, int zone) { + * StringBuilder sql = new StringBuilder("SELECT " + + * "e.group_id, " + + * "(SELECT group_name FROM suyaudavi_kuzhu WHERE suyaudavi_kuzhu.group_id = e.group_id LIMIT 1) AS group_name, " + * + + * "a.enrollment_id, " + + * "e.emp_id, " + + * "e.name, " + + * "e.incharge_id, " + + * "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1) AS salary_per_day, " + * + + * "(SELECT wage_id FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1) AS wage_id, " + * + + * "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS year, " + + * "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS month, " + * + + * "DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime))) AS total_days, " + * + + * "COUNT(DISTINCT DATE(a.indatetime)) AS total_days_present, " + + * "COUNT(DISTINCT CASE WHEN a.indatetime IS NULL THEN DATE(a.oddatetime) END) AS total_days_od, " + * + + * "COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT CASE WHEN a.indatetime IS NULL THEN DATE(a.oddatetime) END) AS total_days_salary, " + * + + * "((COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT CASE WHEN a.indatetime IS NULL THEN DATE(a.oddatetime) END)) * " + * + + * "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1)) AS total_salary, " + * + + * "(MAX(DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)))) - " + * + + * "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT CASE WHEN a.indatetime IS NULL THEN DATE(a.oddatetime) END))) AS total_days_absent, " + * + + * "IFNULL(s.salary_status, '') AS salary_status " + + * "FROM attendance AS a " + + * "INNER JOIN enrollment_table AS e ON a.enrollment_id = e.enrollment_id " + + * "LEFT JOIN salary_details AS s ON a.enrollment_id = s.enrollment_id " + + * "AND s.month = MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) " + * + + * "AND s.year = YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) " + + * "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) " + * ); + * + * // Append condition for incharge_id + * sql.append("AND (? IS NULL OR e.incharge_id = ?) "); + * + * // Append condition for incharge_name + * sql.append("AND (? IS NULL OR e.incharge_name = ?) "); + * + * // Append condition for month if provided + * if (month != null && !month.isEmpty()) { + * sql. + * append("AND MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = ? " + * ); + * } + * + * // Add condition to filter by salary_status (only 'Initiated' or 'Approved') + * sql.append("AND IFNULL(s.salary_status, '') IN ('Initiated', 'Approved') "); + * + * // Group by necessary columns + * sql.append("GROUP BY a.enrollment_id, e.group_id, " + + * "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + + * "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + + * "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1), " + * + + * "(SELECT wage_id FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1), " + * + + * "(SELECT group_name FROM suyaudavi_kuzhu WHERE suyaudavi_kuzhu.group_id = e.group_id LIMIT 1), " + * + + * "DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime))), " + + * "s.salary_status"); + * + * // Create a list of parameters + * List params = new ArrayList<>(); + * params.add(inchargeId); + * params.add(inchargeId); // Added twice for the conditional check in the SQL + * params.add(inchargeName); + * params.add(inchargeName); // Added twice for the conditional check in the SQL + * if (month != null && !month.isEmpty()) { + * params.add(month); + * } + * + * // Log the SQL and parameters (optional for debugging) + * System.out.println("Generated SQL: " + sql.toString()); + * System.out.println("Parameters: " + params); + * + * // Execute the query using JdbcTemplate + * List> results = jdbcTemplate.queryForList(sql.toString(), + * params.toArray()); + * return results; + * } + */ + + public List> getAttendanceWithInitiatedSalary( + int inchargeId, String month, String year, String inchargeName, List enrollmentIds) { + + String sql = "SELECT " + + "e.group_id, " + + "(SELECT group_name FROM suyaudavi_kuzhu WHERE suyaudavi_kuzhu.group_id = e.group_id LIMIT 1) AS group_name, " + + + "a.enrollment_id, e.emp_id, e.name, e.incharge_id, " + + "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1) AS salary_per_day, " + + + "(SELECT wage_id FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1) AS wage_id, " + + "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS year, " + + "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS month, " + + "DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime))) AS total_days, " + + "COUNT(DISTINCT DATE(a.indatetime)) AS total_days_present, " + + "COUNT(DISTINCT CASE WHEN a.indatetime IS NULL THEN DATE(a.oddatetime) END) AS total_days_od, " + + "COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT CASE WHEN a.indatetime IS NULL THEN DATE(a.oddatetime) END) AS total_days_salary, " + + + "((COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT CASE WHEN a.indatetime IS NULL THEN DATE(a.oddatetime) END)) * " + + + "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1)) AS total_salary, " + + + "(MAX(DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)))) - " + + "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT CASE WHEN a.indatetime IS NULL THEN DATE(a.oddatetime) END))) AS total_days_absent, " + + + "IFNULL(s.salary_status, '') AS salary_status " + + "FROM attendance AS a " + + "INNER JOIN enrollment_table AS e ON a.enrollment_id = e.enrollment_id " + + "LEFT JOIN salary_details AS s ON a.enrollment_id = s.enrollment_id " + + "AND s.month = MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) " + + "AND s.year = YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) " + + "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) " + + "AND (? IS NULL OR e.incharge_id = ?) " + + "AND (? IS NULL OR e.incharge_name = ?) "; + + if (month != null && !month.isEmpty()) { + sql += "AND MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = ? "; } + if (year != null && !year.isEmpty()) { + sql += "AND YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = ? "; + } + + // Assuming enrollmentIds is a List or List + StringBuilder placeholders = new StringBuilder(); + for (int i = 0; i < enrollmentIds.size(); i++) { + placeholders.append("?"); + if (i < enrollmentIds.size() - 1) { + placeholders.append(", "); + } + } + String inClause = placeholders.toString() + ") "; + + sql += "AND IFNULL(s.salary_status, '') IN ('Initiated', 'Approved') " + + "AND e.enrollment_id IN (" + + inClause + + "GROUP BY a.enrollment_id, e.group_id, " + + "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + + "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + + "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1), " + + "(SELECT wage_id FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1), " + + "(SELECT group_name FROM suyaudavi_kuzhu WHERE suyaudavi_kuzhu.group_id = e.group_id LIMIT 1), " + + "DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime))), " + + "s.salary_status"; + + List params = new ArrayList<>(); + params.add(inchargeId); + params.add(inchargeId); + params.add(inchargeName); + params.add(inchargeName); + + if (month != null && !month.isEmpty()) { + params.add(month); + } + if (year != null && !year.isEmpty()) { + params.add(year); + } + + params.addAll(enrollmentIds); + + System.out.println("SQL = " + sql); + System.out.println("Parameter = " + params); + + return jdbcTemplate.queryForList(sql, params.toArray()); + } + @Transactional public void updateSalaryStatusToApproved(List enrollmentIds, String month, int year) { - String sql = "UPDATE salary_details SET salary_status = 'Approved' WHERE enrollment_id = ? AND month = ? AND year = ?"; - - for (Integer enrollmentId : enrollmentIds) { - // Pass the individual enrollmentId instead of the entire list - jdbcTemplate.update(sql, enrollmentId, month, year); - } - } - /* - public List> getFilteredSalaryDetails(String month, Integer year, String salaryStatus) { - StringBuilder sql = new StringBuilder("SELECT " + - "e.incharge_name, " + - "GROUP_CONCAT(e.enrollment_id) AS enrollment_ids, " + - "COUNT(e.enrollment_id) AS total_staff_count, " + - "sd.month, " + - "sd.year, " + - "sd.salary_status, " + - "COUNT(CASE WHEN sd.salary_status = 'Initiated' THEN 1 END) AS total_initiated_count, " + - "COUNT(CASE WHEN sd.salary_status = 'Approved' THEN 1 END) AS total_approved_count, " + - "SUM(CASE WHEN sd.salary_status IN ('Initiated', 'Approved') THEN sd.salary_amount ELSE 0 END) AS total_salary_amount " + - "FROM enrollment_table e " + - "JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " + - "WHERE 1=1 "); // Placeholder for dynamic conditions - - if (month != null && !month.isEmpty()) { - sql.append(" AND sd.month = '").append(month).append("'"); - } - if (year != null) { - sql.append(" AND sd.year = ").append(year); - } - if (salaryStatus != null && !salaryStatus.isEmpty()) { - sql.append(" AND sd.salary_status = '").append(salaryStatus).append("'"); - } - - sql.append(" GROUP BY e.incharge_name, sd.month, sd.year, sd.salary_status "); - sql.append(" ORDER BY sd.year DESC, sd.month DESC"); - - try { - List> result = jdbcTemplate.queryForList(sql.toString()); - for (Map row : result) { - String enrollmentIdsString = (String) row.get("enrollment_ids"); - if (enrollmentIdsString != null) { - List enrollmentIds = Arrays.stream(enrollmentIdsString.split(",")) - .map(String::trim) - .filter(id -> !id.isEmpty()) - .map(Integer::parseInt) - .collect(Collectors.toList()); - row.put("enrollment_ids", enrollmentIds); - } - } - return result; - } catch (Exception e) { - e.printStackTrace(); - return Collections.emptyList(); - } + String sql = "UPDATE salary_details SET salary_status = 'Approved' WHERE enrollment_id = ? AND month = ? AND year = ?"; + + for (Integer enrollmentId : enrollmentIds) { + // Pass the individual enrollmentId instead of the entire list + jdbcTemplate.update(sql, enrollmentId, month, year); + } } - */ /* - public List> getFilteredSalaryDetails(String month, Integer year, String salaryStatus, String department, String loginId) { - StringBuilder sql = new StringBuilder("SELECT " + - "e.incharge_name, " + - "GROUP_CONCAT(e.enrollment_id) AS enrollment_ids, " + - "COUNT(e.enrollment_id) AS total_staff_count, " + - "sd.month, " + - "sd.year, " + - "sd.salary_status, " + - "COUNT(CASE WHEN sd.salary_status = 'Initiated' THEN 1 END) AS total_initiated_count, " + - "COUNT(CASE WHEN sd.salary_status = 'Approved' THEN 1 END) AS total_approved_count, " + - "SUM(CASE WHEN sd.salary_status IN ('Initiated', 'Approved') THEN sd.salary_amount ELSE 0 END) AS total_salary_amount, " + - "e.department " + // Select the department as well - "FROM enrollment_table e " + - "JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " + - "WHERE 1=1 "); // Placeholder for dynamic conditions - - // Add filters for month, year, salary status, and department - if (month != null && !month.isEmpty()) { - sql.append(" AND sd.month = '").append(month).append("'"); - } - if (year != null) { - sql.append(" AND sd.year = ").append(year); - } - if (salaryStatus != null && !salaryStatus.isEmpty()) { - sql.append(" AND sd.salary_status = '").append(salaryStatus).append("'"); - } - if (department != null && !department.isEmpty()) { - sql.append(" AND e.department = '").append(department).append("'"); - } - - // Retrieve zone access for the user - String zoneAccessSQL = "SELECT zone FROM gcc_apps.login_mapping_user WHERE appuser_id = ?"; - List> getAccess = jdbcTemplate.queryForList(zoneAccessSQL, loginId); - System.out.println(zoneAccessSQL +"->"+ loginId); - // Extract the zones from getAccess - List zones = getAccess.stream() - .map(access -> (String) access.get("zone")) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - - // If the user has zone acc ess, add it to the WHERE clause - if (!zones.isEmpty()) { - String zoneList = zones.stream() - .map(zone -> "'" + zone + "'") - .collect(Collectors.joining(", ")); - sql.append(" AND e.zone IN (").append(zoneList).append(")"); - // System.out.println("AND e.zone IN ("+zoneList+")"); - } - else { - sql.append(" AND e.zone IN (").append("0").append(")"); - } - - sql.append(" GROUP BY e.incharge_name, sd.month, sd.year, sd.salary_status, e.department "); - sql.append(" ORDER BY sd.year DESC, sd.month DESC"); - - System.out.println(sql); - - try { - List> result = jdbcTemplate.queryForList(sql.toString()); - for (Map row : result) { - String enrollmentIdsString = (String) row.get("enrollment_ids"); - if (enrollmentIdsString != null) { - List enrollmentIds = Arrays.stream(enrollmentIdsString.split(",")) - .map(String::trim) - .filter(id -> !id.isEmpty()) - .map(Integer::parseInt) - .collect(Collectors.toList()); - row.put("enrollment_ids", enrollmentIds); - } - } - return result; - } catch (Exception e) { - e.printStackTrace(); - return Collections.emptyList(); - } + * public List> getFilteredSalaryDetails(String month, + * Integer year, String salaryStatus) { + * StringBuilder sql = new StringBuilder("SELECT " + + * "e.incharge_name, " + + * "GROUP_CONCAT(e.enrollment_id) AS enrollment_ids, " + + * "COUNT(e.enrollment_id) AS total_staff_count, " + + * "sd.month, " + + * "sd.year, " + + * "sd.salary_status, " + + * "COUNT(CASE WHEN sd.salary_status = 'Initiated' THEN 1 END) AS total_initiated_count, " + * + + * "COUNT(CASE WHEN sd.salary_status = 'Approved' THEN 1 END) AS total_approved_count, " + * + + * "SUM(CASE WHEN sd.salary_status IN ('Initiated', 'Approved') THEN sd.salary_amount ELSE 0 END) AS total_salary_amount " + * + + * "FROM enrollment_table e " + + * "JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " + + * "WHERE 1=1 "); // Placeholder for dynamic conditions + * + * if (month != null && !month.isEmpty()) { + * sql.append(" AND sd.month = '").append(month).append("'"); + * } + * if (year != null) { + * sql.append(" AND sd.year = ").append(year); + * } + * if (salaryStatus != null && !salaryStatus.isEmpty()) { + * sql.append(" AND sd.salary_status = '").append(salaryStatus).append("'"); + * } + * + * sql.append(" GROUP BY e.incharge_name, sd.month, sd.year, sd.salary_status " + * ); + * sql.append(" ORDER BY sd.year DESC, sd.month DESC"); + * + * try { + * List> result = jdbcTemplate.queryForList(sql.toString()); + * for (Map row : result) { + * String enrollmentIdsString = (String) row.get("enrollment_ids"); + * if (enrollmentIdsString != null) { + * List enrollmentIds = Arrays.stream(enrollmentIdsString.split(",")) + * .map(String::trim) + * .filter(id -> !id.isEmpty()) + * .map(Integer::parseInt) + * .collect(Collectors.toList()); + * row.put("enrollment_ids", enrollmentIds); + * } + * } + * return result; + * } catch (Exception e) { + * e.printStackTrace(); + * return Collections.emptyList(); + * } + * } + */ + /* + * public List> getFilteredSalaryDetails(String month, + * Integer year, String salaryStatus, String department, String loginId) { + * StringBuilder sql = new StringBuilder("SELECT " + + * "e.incharge_name, " + + * "GROUP_CONCAT(e.enrollment_id) AS enrollment_ids, " + + * "COUNT(e.enrollment_id) AS total_staff_count, " + + * "sd.month, " + + * "sd.year, " + + * "sd.salary_status, " + + * "COUNT(CASE WHEN sd.salary_status = 'Initiated' THEN 1 END) AS total_initiated_count, " + * + + * "COUNT(CASE WHEN sd.salary_status = 'Approved' THEN 1 END) AS total_approved_count, " + * + + * "SUM(CASE WHEN sd.salary_status IN ('Initiated', 'Approved') THEN sd.salary_amount ELSE 0 END) AS total_salary_amount, " + * + + * "e.department " + // Select the department as well + * "FROM enrollment_table e " + + * "JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " + + * "WHERE 1=1 "); // Placeholder for dynamic conditions + * + * // Add filters for month, year, salary status, and department + * if (month != null && !month.isEmpty()) { + * sql.append(" AND sd.month = '").append(month).append("'"); + * } + * if (year != null) { + * sql.append(" AND sd.year = ").append(year); + * } + * if (salaryStatus != null && !salaryStatus.isEmpty()) { + * sql.append(" AND sd.salary_status = '").append(salaryStatus).append("'"); + * } + * if (department != null && !department.isEmpty()) { + * sql.append(" AND e.department = '").append(department).append("'"); + * } + * + * // Retrieve zone access for the user + * String zoneAccessSQL = + * "SELECT zone FROM gcc_apps.login_mapping_user WHERE appuser_id = ?"; + * List> getAccess = + * jdbcTemplate.queryForList(zoneAccessSQL, loginId); + * System.out.println(zoneAccessSQL +"->"+ loginId); + * // Extract the zones from getAccess + * List zones = getAccess.stream() + * .map(access -> (String) access.get("zone")) + * .filter(Objects::nonNull) + * .collect(Collectors.toList()); + * + * // If the user has zone acc ess, add it to the WHERE clause + * if (!zones.isEmpty()) { + * String zoneList = zones.stream() + * .map(zone -> "'" + zone + "'") + * .collect(Collectors.joining(", ")); + * sql.append(" AND e.zone IN (").append(zoneList).append(")"); + * // System.out.println("AND e.zone IN ("+zoneList+")"); + * } + * else { + * sql.append(" AND e.zone IN (").append("0").append(")"); + * } + * + * sql. + * append(" GROUP BY e.incharge_name, sd.month, sd.year, sd.salary_status, e.department " + * ); + * sql.append(" ORDER BY sd.year DESC, sd.month DESC"); + * + * System.out.println(sql); + * + * try { + * List> result = jdbcTemplate.queryForList(sql.toString()); + * for (Map row : result) { + * String enrollmentIdsString = (String) row.get("enrollment_ids"); + * if (enrollmentIdsString != null) { + * List enrollmentIds = Arrays.stream(enrollmentIdsString.split(",")) + * .map(String::trim) + * .filter(id -> !id.isEmpty()) + * .map(Integer::parseInt) + * .collect(Collectors.toList()); + * row.put("enrollment_ids", enrollmentIds); + * } + * } + * return result; + * } catch (Exception e) { + * e.printStackTrace(); + * return Collections.emptyList(); + * } + * } + */ + + public List> getFilteredSalaryDetails(String month, Integer year, String salaryStatus, + String loginId) { + StringBuilder sql = new StringBuilder("SELECT " + + "e.incharge_name, " + + "e.incharge_id, " + + "e.zone, " + + "GROUP_CONCAT(e.enrollment_id) AS enrollment_ids, " + + "COUNT(e.enrollment_id) AS total_staff_count, " + + "sd.month, " + + "sd.year, " + + "sd.salary_status, " + + "COUNT(CASE WHEN sd.salary_status = 'Initiated' THEN 1 END) AS total_initiated_count, " + + "COUNT(CASE WHEN sd.salary_status = 'Approved' THEN 1 END) AS total_approved_count, " + + "SUM(CASE WHEN sd.salary_status IN ('Initiated', 'Approved') THEN sd.salary_amount ELSE 0 END) AS total_salary_amount, " + + + "e.department " + // Select the department as well + "FROM enrollment_table e " + + "JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " + + "WHERE 1=1 "); // Placeholder for dynamic conditions + + // Add filters for month, year, salary status, and department + if (month != null && !month.isEmpty()) { + sql.append(" AND sd.month = '").append(month).append("'"); + } + if (year != null) { + sql.append(" AND sd.year = ").append(year); + } + if (salaryStatus != null && !salaryStatus.isEmpty()) { + sql.append(" AND sd.salary_status = '").append(salaryStatus).append("'"); + } + + // Retrieve zone access for the user + String zoneAccessSQL = "SELECT zone FROM gcc_apps.login_mapping_user WHERE appuser_id = ?"; + List> getAccess = jdbcTemplate.queryForList(zoneAccessSQL, loginId); + System.out.println(zoneAccessSQL + "->" + loginId); + // Extract the zones from getAccess + /* + * List zones = getAccess.stream() + * .map(access -> (String) access.get("zone")) + * .filter(Objects::nonNull) + * .collect(Collectors.toList()); + * + * // If the user has zone acc ess, add it to the WHERE clause + * if (!zones.isEmpty()) { + * String zoneList = zones.stream() + * .map(zone -> "'" + zone + "'") + * .collect(Collectors.joining(", ")); + * sql.append(" AND e.zone IN (").append(zoneList).append(")"); + * // System.out.println("AND e.zone IN ("+zoneList+")"); + * } + * else { + * sql.append(" AND e.zone IN (").append("0").append(")"); + * } + */ + // Extract zones from getAccess + List zones = new ArrayList(); + for (Map access : getAccess) { + Object zoneObj = access.get("zone"); + if (zoneObj != null) { + zones.add(zoneObj.toString()); + } + } + + // If the user has zone access, add it to the WHERE clause + if (!zones.isEmpty()) { + StringBuilder zoneList = new StringBuilder(); + for (int i = 0; i < zones.size(); i++) { + zoneList.append("'").append(zones.get(i)).append("'"); + if (i < zones.size() - 1) { + zoneList.append(", "); + } + } + sql.append(" AND e.zone IN (").append(zoneList.toString()).append(")"); + } else { + sql.append(" AND e.zone IN (0)"); + } + sql.append( + " GROUP BY e.incharge_name, e.incharge_id, e.zone, sd.month, sd.year, sd.salary_status, e.department "); + sql.append(" ORDER BY sd.year DESC, sd.month DESC"); + /* + * try { + * List> result = jdbcTemplate.queryForList(sql.toString()); + * for (Map row : result) { + * String enrollmentIdsString = (String) row.get("enrollment_ids"); + * if (enrollmentIdsString != null) { + * List enrollmentIds = Arrays.stream(enrollmentIdsString.split(",")) + * .map(String::trim) + * .filter(id -> !id.isEmpty()) + * .map(Integer::parseInt) + * .collect(Collectors.toList()); + * row.put("enrollment_ids", enrollmentIds); + * } + * } + * return result; + * } catch (Exception e) { + * e.printStackTrace(); + * return Collections.emptyList(); + * } + */ + + try { + List> result = jdbcTemplate.queryForList(sql.toString()); + + for (Map row : result) { + String enrollmentIdsString = (String) row.get("enrollment_ids"); + if (enrollmentIdsString != null) { + String[] parts = enrollmentIdsString.split(","); + List enrollmentIds = new ArrayList(); + for (int i = 0; i < parts.length; i++) { + String part = parts[i].trim(); + if (!part.isEmpty()) { + try { + enrollmentIds.add(Integer.parseInt(part)); + } catch (NumberFormatException nfe) { + // Ignore or log invalid integers + nfe.printStackTrace(); + } + } + } + row.put("enrollment_ids", enrollmentIds); + } + } + + return result; + } catch (Exception e) { + e.printStackTrace(); + return Collections.emptyList(); + } + } - */ - - public List> getFilteredSalaryDetails(String month, Integer year, String salaryStatus, String loginId) { - StringBuilder sql = new StringBuilder("SELECT " + - "e.incharge_name, " + - "e.incharge_id, " + - "e.zone, " + - "GROUP_CONCAT(e.enrollment_id) AS enrollment_ids, " + - "COUNT(e.enrollment_id) AS total_staff_count, " + - "sd.month, " + - "sd.year, " + - "sd.salary_status, " + - "COUNT(CASE WHEN sd.salary_status = 'Initiated' THEN 1 END) AS total_initiated_count, " + - "COUNT(CASE WHEN sd.salary_status = 'Approved' THEN 1 END) AS total_approved_count, " + - "SUM(CASE WHEN sd.salary_status IN ('Initiated', 'Approved') THEN sd.salary_amount ELSE 0 END) AS total_salary_amount, " + - "e.department " + // Select the department as well - "FROM enrollment_table e " + - "JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " + - "WHERE 1=1 "); // Placeholder for dynamic conditions - - // Add filters for month, year, salary status, and department - if (month != null && !month.isEmpty()) { - sql.append(" AND sd.month = '").append(month).append("'"); - } - if (year != null) { - sql.append(" AND sd.year = ").append(year); - } - if (salaryStatus != null && !salaryStatus.isEmpty()) { - sql.append(" AND sd.salary_status = '").append(salaryStatus).append("'"); - } - - - // Retrieve zone access for the user - String zoneAccessSQL = "SELECT zone FROM gcc_apps.login_mapping_user WHERE appuser_id = ?"; - List> getAccess = jdbcTemplate.queryForList(zoneAccessSQL, loginId); - System.out.println(zoneAccessSQL +"->"+ loginId); - // Extract the zones from getAccess - /*List zones = getAccess.stream() - .map(access -> (String) access.get("zone")) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - - // If the user has zone acc ess, add it to the WHERE clause - if (!zones.isEmpty()) { - String zoneList = zones.stream() - .map(zone -> "'" + zone + "'") - .collect(Collectors.joining(", ")); - sql.append(" AND e.zone IN (").append(zoneList).append(")"); - // System.out.println("AND e.zone IN ("+zoneList+")"); - } - else { - sql.append(" AND e.zone IN (").append("0").append(")"); - } - */ - // Extract zones from getAccess - List zones = new ArrayList(); - for (Map access : getAccess) { - Object zoneObj = access.get("zone"); - if (zoneObj != null) { - zones.add(zoneObj.toString()); - } - } - - // If the user has zone access, add it to the WHERE clause - if (!zones.isEmpty()) { - StringBuilder zoneList = new StringBuilder(); - for (int i = 0; i < zones.size(); i++) { - zoneList.append("'").append(zones.get(i)).append("'"); - if (i < zones.size() - 1) { - zoneList.append(", "); - } - } - sql.append(" AND e.zone IN (").append(zoneList.toString()).append(")"); - } else { - sql.append(" AND e.zone IN (0)"); - } - sql.append(" GROUP BY e.incharge_name, e.incharge_id, e.zone, sd.month, sd.year, sd.salary_status, e.department "); - sql.append(" ORDER BY sd.year DESC, sd.month DESC"); -/* - try { - List> result = jdbcTemplate.queryForList(sql.toString()); - for (Map row : result) { - String enrollmentIdsString = (String) row.get("enrollment_ids"); - if (enrollmentIdsString != null) { - List enrollmentIds = Arrays.stream(enrollmentIdsString.split(",")) - .map(String::trim) - .filter(id -> !id.isEmpty()) - .map(Integer::parseInt) - .collect(Collectors.toList()); - row.put("enrollment_ids", enrollmentIds); - } - } - return result; - } catch (Exception e) { - e.printStackTrace(); - return Collections.emptyList(); - } - */ - - try { - List> result = jdbcTemplate.queryForList(sql.toString()); - - for (Map row : result) { - String enrollmentIdsString = (String) row.get("enrollment_ids"); - if (enrollmentIdsString != null) { - String[] parts = enrollmentIdsString.split(","); - List enrollmentIds = new ArrayList(); - for (int i = 0; i < parts.length; i++) { - String part = parts[i].trim(); - if (!part.isEmpty()) { - try { - enrollmentIds.add(Integer.parseInt(part)); - } catch (NumberFormatException nfe) { - // Ignore or log invalid integers - nfe.printStackTrace(); - } - } - } - row.put("enrollment_ids", enrollmentIds); - } - } - - return result; - } catch (Exception e) { - e.printStackTrace(); - return Collections.emptyList(); - } - + + public Integer checkInchargeID(Integer inchargeId) { + + String sql = "SELECT EXISTS( " + + "SELECT 1 FROM additional_incharge " + + "WHERE incharge_id = ? AND is_active = 1 AND is_delete = 0)"; + + Integer result = jdbcTemplate.queryForObject(sql, Integer.class, inchargeId); + + return result; } - - public List> getAttendanceWithSalaryByInchargeId(String month, Integer year, Integer incharge_id) { - StringBuilder sql = new StringBuilder("SELECT " + - "e.group_id, " + - "(SELECT group_name FROM suyaudavi_kuzhu WHERE suyaudavi_kuzhu.group_id = e.group_id LIMIT 1) AS group_name, " + - "a.enrollment_id, " + - "e.emp_id, " + - "e.name, " + - "e.incharge_id, " + - "e.incharge_name, " + - "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1) AS salary_per_day, " + - "(SELECT wage_id FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1) AS wage_id, " + - "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS year, " + - "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS month, " + - "DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime))) AS total_days, " + - "COUNT(DISTINCT DATE(a.indatetime)) AS total_days_present, " + - // Subquery to get total_days_od - "(SELECT COUNT(DISTINCT DATE(a2.oddatetime)) " + - " FROM attendance AS a2 " + - " WHERE MONTHNAME(a2.oddatetime) = ? " + // Use placeholder for month - " AND YEAR(a2.oddatetime) = ? " + // Use placeholder for year - " AND a2.enrollment_id = a.enrollment_id " + - " AND DATE(a2.oddatetime) NOT IN ( " + - " SELECT DISTINCT DATE(a3.indatetime) " + - " FROM attendance AS a3 " + - " WHERE MONTHNAME(a3.indatetime) = ? " + // Use placeholder for month - " AND YEAR(a3.indatetime) = ? " + // Use placeholder for year - " AND a3.enrollment_id = a.enrollment_id " + - ")) AS total_days_od, " + - "IFNULL(s.salary_status, '') AS salary_status " + - "FROM attendance AS a " + - "INNER JOIN enrollment_table AS e ON a.enrollment_id = e.enrollment_id " + - "LEFT JOIN salary_details AS s ON a.enrollment_id = s.enrollment_id " + - "AND s.month = MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) " + - "AND s.year = YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) " + - "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) "); - - // Append condition for incharge_id - sql.append("AND (? IS NULL OR e.incharge_id = ?) "); - - // Append condition for month if provided - if (month != null && !month.isEmpty()) { - sql.append("AND MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = ? "); - } - - // Append condition for year if provided - if (year != null) { - sql.append("AND YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = ? "); - } - - // Group by necessary columns - sql.append("GROUP BY a.enrollment_id, e.group_id, " + - "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + - "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + - "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1), " + - "(SELECT wage_id FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1), " + - "(SELECT group_name FROM suyaudavi_kuzhu WHERE suyaudavi_kuzhu.group_id = e.group_id LIMIT 1), " + - "DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime))), " + - "s.salary_status"); - - // Create a list of parameters - List params = new ArrayList<>(); - params.add(month); // Add month for total_days_od - params.add(year); // Add year for total_days_od - params.add(month); // Add month for the inner subquery - params.add(year); // Add year for the inner subquery - params.add(incharge_id); - params.add(incharge_id); // Added twice for the conditional check in the SQL - if (month != null && !month.isEmpty()) { - params.add(month); - } - if (year != null) { - params.add(year); - } - - // Log the SQL and parameters (optional for debugging) - System.out.println("Generated SQL: " + sql.toString()); - System.out.println("Parameters: " + params); - - // Execute the query using JdbcTemplate - List> results = jdbcTemplate.queryForList(sql.toString(), params.toArray()); - return results; + + public List> getAttendanceWithSalaryByInchargeId(String month, Integer year, + Integer incharge_id) { + StringBuilder sql = new StringBuilder("SELECT " + + "e.group_id, " + + "(SELECT group_name FROM suyaudavi_kuzhu WHERE suyaudavi_kuzhu.group_id = e.group_id LIMIT 1) AS group_name, " + + + "a.enrollment_id, " + + "e.emp_id, " + + "e.name, " + + "e.incharge_id, " + + "e.incharge_name, " + + "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1) AS salary_per_day, " + + + "(SELECT wage_id FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1) AS wage_id, " + + "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS year, " + + "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS month, " + + "DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime))) AS total_days, " + + "COUNT(DISTINCT DATE(a.indatetime)) AS total_days_present, " + + // Subquery to get total_days_od + "(SELECT COUNT(DISTINCT DATE(a2.oddatetime)) " + + " FROM attendance AS a2 " + + " WHERE MONTHNAME(a2.oddatetime) = ? " + // Use placeholder for month + " AND YEAR(a2.oddatetime) = ? " + // Use placeholder for year + " AND a2.enrollment_id = a.enrollment_id " + + " AND DATE(a2.oddatetime) NOT IN ( " + + " SELECT DISTINCT DATE(a3.indatetime) " + + " FROM attendance AS a3 " + + " WHERE MONTHNAME(a3.indatetime) = ? " + // Use placeholder for month + " AND YEAR(a3.indatetime) = ? " + // Use placeholder for year + " AND a3.enrollment_id = a.enrollment_id " + + ")) AS total_days_od, " + + "IFNULL(s.salary_status, '') AS salary_status " + + "FROM attendance AS a " + + "INNER JOIN enrollment_table AS e ON a.enrollment_id = e.enrollment_id " + + "LEFT JOIN salary_details AS s ON a.enrollment_id = s.enrollment_id " + + "AND s.month = MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) " + + "AND s.year = YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) " + + "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) "); + + // Append condition for incharge_id + sql.append("AND (? IS NULL OR e.incharge_id = ?) "); + + // Append condition for month if provided + if (month != null && !month.isEmpty()) { + sql.append("AND MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = ? "); + } + + // Append condition for year if provided + if (year != null) { + sql.append("AND YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = ? "); + } + + // Group by necessary columns + sql.append("GROUP BY a.enrollment_id, e.group_id, " + + "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + + "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + + "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1), " + + "(SELECT wage_id FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1), " + + "(SELECT group_name FROM suyaudavi_kuzhu WHERE suyaudavi_kuzhu.group_id = e.group_id LIMIT 1), " + + "DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime))), " + + "s.salary_status"); + + // Create a list of parameters + List params = new ArrayList<>(); + params.add(month); // Add month for total_days_od + params.add(year); // Add year for total_days_od + params.add(month); // Add month for the inner subquery + params.add(year); // Add year for the inner subquery + params.add(incharge_id); + params.add(incharge_id); // Added twice for the conditional check in the SQL + if (month != null && !month.isEmpty()) { + params.add(month); + } + if (year != null) { + params.add(year); + } + + // Log the SQL and parameters (optional for debugging) + System.out.println("Generated SQL: " + sql.toString()); + System.out.println("Parameters: " + params); + + // Execute the query using JdbcTemplate + List> results = jdbcTemplate.queryForList(sql.toString(), params.toArray()); + return results; } - - public List> getZoneWiseReport(String month, Integer year, String salaryStatus, String groupName, String zone, String division) { + + public List> getZoneWiseReport(String month, Integer year, String salaryStatus, + String groupName, String zone, String division) { String sql = "select en.zone,en.division, en.emp_id, en.name, en.incharge_name, en.incharge_designation, sk.group_name, s.total_days_present, s.total_days_od, " + "s.total_days_absent, s.total_days_salary, s.month as imonth,s.year as iyear, s.salary_status, s.salary_amount as total_salary, " + "DAY(LAST_DAY(STR_TO_DATE(CONCAT(s.year, '-', s.month, '-01'), '%Y-%M-%d'))) AS total_days from salary_details s " + "left join enrollment_table en on s.enrollment_id = en.enrollment_id " + "left join suyaudavi_kuzhu sk on s.group_id = sk.group_id " + "where s.month = ? and s.year =? " - + "AND (s.salary_status = 'Initiated' OR s.salary_status = 'Approved') " - + (salaryStatus != null && !salaryStatus.isEmpty() ? "AND s.salary_status = ? " : "") - + (groupName != null && !groupName.isEmpty() ? "AND sk.group_name = ? " : "") - + (zone != null && !zone.isEmpty() ? "AND en.zone = ? " : "") - + (division != null && !division.isEmpty() ? "AND en.division = ? " : ""); - + + "AND (s.salary_status = 'Initiated' OR s.salary_status = 'Approved') " + + (salaryStatus != null && !salaryStatus.isEmpty() ? "AND s.salary_status = ? " : "") + + (groupName != null && !groupName.isEmpty() ? "AND sk.group_name = ? " : "") + + (zone != null && !zone.isEmpty() ? "AND en.zone = ? " : "") + + (division != null && !division.isEmpty() ? "AND en.division = ? " : ""); + // Prepare the query parameters based on provided inputs - List params = new ArrayList<>(); - params.add(month); - params.add(year); - if (salaryStatus != null && !salaryStatus.isEmpty()) { - params.add(salaryStatus); - } - if (groupName != null && !groupName.isEmpty()) { - params.add(groupName); - } - if (zone != null && !zone.isEmpty()) { - params.add(zone); - } - if (division != null && !division.isEmpty()) { - params.add(division); - } - - + List params = new ArrayList<>(); + params.add(month); + params.add(year); + if (salaryStatus != null && !salaryStatus.isEmpty()) { + params.add(salaryStatus); + } + if (groupName != null && !groupName.isEmpty()) { + params.add(groupName); + } + if (zone != null && !zone.isEmpty()) { + params.add(zone); + } + if (division != null && !division.isEmpty()) { + params.add(division); + } + List> results = jdbcTemplate.queryForList(sql.toString(), params.toArray()); - return results; + return results; } - - public List> getAttendanceReport(String fromdate, String todate, String groupName, String zone, String division) { + + public List> getAttendanceReport(String fromdate, String todate, String groupName, String zone, + String division) { String sql = "select date_format(coalesce(att.indatetime, att.oddatetime, att.leavedatetime),'%d-%m-%Y') as attendance_date, et.emp_id, et.name, " + " CASE WHEN att.indatetime IS NOT NULL THEN 'Present' WHEN att.leavedatetime IS NOT NULL THEN 'Absent' " + " WHEN att.oddatetime IS NOT NULL THEN 'On Duty' ELSE 'No Record' END AS attendance_status, " + " et.incharge_name,et.incharge_phoneno, et.incharge_designation, et.zone, et.division, et.department, sk.group_name from attendance att " + " left join enrollment_table et on att.enrollment_id = et.enrollment_id " + " left join suyaudavi_kuzhu sk on et.group_id = sk.group_id where " - + " (DATE(att.indatetime) BETWEEN STR_TO_DATE('"+fromdate+"', '%Y-%m-%d') AND STR_TO_DATE('"+todate+"', '%Y-%m-%d') " - + " OR DATE(att.oddatetime) BETWEEN STR_TO_DATE('"+fromdate+"', '%Y-%m-%d') AND STR_TO_DATE('"+todate+"', '%Y-%m-%d')" - + " OR DATE(att.leavedatetime) BETWEEN STR_TO_DATE('"+fromdate+"', '%Y-%m-%d') AND STR_TO_DATE('"+todate+"', '%Y-%m-%d')) " + + " (DATE(att.indatetime) BETWEEN STR_TO_DATE('" + fromdate + "', '%Y-%m-%d') AND STR_TO_DATE('" + + todate + "', '%Y-%m-%d') " + + " OR DATE(att.oddatetime) BETWEEN STR_TO_DATE('" + fromdate + "', '%Y-%m-%d') AND STR_TO_DATE('" + + todate + "', '%Y-%m-%d')" + + " OR DATE(att.leavedatetime) BETWEEN STR_TO_DATE('" + fromdate + "', '%Y-%m-%d') AND STR_TO_DATE('" + + todate + "', '%Y-%m-%d')) " + (zone != null && !zone.isEmpty() ? " and et.zone = ? " : "") - + (division != null && !division.isEmpty() ?" and et.division = ? " : "") - + (groupName != null && !groupName.isEmpty() ?" and sk.group_name = ? " : ""); - + + (division != null && !division.isEmpty() ? " and et.division = ? " : "") + + (groupName != null && !groupName.isEmpty() ? " and sk.group_name = ? " : ""); + // Prepare the query parameters based on provided inputs - List params = new ArrayList<>(); - - if (groupName != null && !groupName.isEmpty()) { - params.add(groupName); - } - if (zone != null && !zone.isEmpty()) { - params.add(zone); - } - if (division != null && !division.isEmpty()) { - params.add(division); - } - + List params = new ArrayList<>(); + + if (groupName != null && !groupName.isEmpty()) { + params.add(groupName); + } + if (zone != null && !zone.isEmpty()) { + params.add(zone); + } + if (division != null && !division.isEmpty()) { + params.add(division); + } + List> results = jdbcTemplate.queryForList(sql.toString(), params.toArray()); - return results; + return results; } - /**************************************Updated code working 08-10-2024******************************************/ -// public List> getAttendanceWithSalaryByInchargeId(String month, Integer year, Integer incharge_id) { -// StringBuilder sql = new StringBuilder("SELECT " + -// "e.group_id, " + -// "(SELECT group_name FROM suyaudavi_kuzhu WHERE suyaudavi_kuzhu.group_id = e.group_id LIMIT 1) AS group_name, " + -// "a.enrollment_id, " + -// "e.emp_id, " + -// "e.name, " + -// "e.incharge_id, " + -// "e.incharge_name, " + -// "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1) AS salary_per_day, " + -// "(SELECT wage_id FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1) AS wage_id, " + -// "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS year, " + -// "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS month, " + -// "DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime))) AS total_days, " + -// "COUNT(DISTINCT DATE(a.indatetime)) AS total_days_present, " + -// "COUNT(DISTINCT DATE(a.oddatetime)) AS total_days_od, " + -// "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) AS total_days_salary, " + -// "((COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) * " + -// "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1)) AS total_salary, " + -// "(MAX(DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)))) - " + -// "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime)))) AS total_days_absent, " + -// "IFNULL(s.salary_status, '') AS salary_status " + -// "FROM attendance AS a " + -// "INNER JOIN enrollment_table AS e ON a.enrollment_id = e.enrollment_id " + -// "LEFT JOIN salary_details AS s ON a.enrollment_id = s.enrollment_id " + -// "AND s.month = MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) " + -// "AND s.year = YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) " + -// "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) "); -// -// // Append condition for incharge_id -// sql.append("AND (? IS NULL OR e.incharge_id = ?) "); -// -// // Append condition for month if provided -// if (month != null && !month.isEmpty()) { -// sql.append("AND MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = ? "); -// } -// -// // Append condition for year if provided -// if (year != null) { -// sql.append("AND YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = ? "); -// } -// -// // Group by necessary columns -// sql.append("GROUP BY a.enrollment_id, e.group_id, " + -// "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + -// "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + -// "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1), " + -// "(SELECT wage_id FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC LIMIT 1), " + -// "(SELECT group_name FROM suyaudavi_kuzhu WHERE suyaudavi_kuzhu.group_id = e.group_id LIMIT 1), " + -// "DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime))), " + -// "s.salary_status"); -// -// // Create a list of parameters -// List params = new ArrayList<>(); -// params.add(incharge_id); -// params.add(incharge_id); // Added twice for the conditional check in the SQL -// if (month != null && !month.isEmpty()) { -// params.add(month); -// } -// if (year != null) { -// params.add(year); -// } -// -// // Log the SQL and parameters (optional for debugging) -// System.out.println("Generated SQL: " + sql.toString()); -// System.out.println("Parameters: " + params); -// -// // Execute the query using JdbcTemplate -// List> results = jdbcTemplate.queryForList(sql.toString(), params.toArray()); -// return results; -// } - -// public List> getAttendanceWithSalaryByInchargeId(String month, Integer year, Integer incharge_id) { -// StringBuilder sql = new StringBuilder("SELECT " + -// "e.enrollment_id, " + -// "e.emp_id, " + -// "e.name, " + -// "e.incharge_id, " + -// "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS year, " + -// "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS month, " + -// "COUNT(DISTINCT DATE(a.indatetime)) AS total_days_present, " + -// "COUNT(DISTINCT DATE(a.oddatetime)) AS total_days_od, " + -// "MAX(DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)))) AS total_days, " + -// "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) AS total_days_salary, " + -// "(MAX(DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)))) - " + -// "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime)))) AS total_days_absent, " + -// "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1) AS salary_per_day, " + -// "((COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) * " + -// "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1)) AS total_salary, " + -// "IFNULL(sd.salary_status, '') AS salary_status, " + // Modified salary_status to return an empty string -// "sk.group_id, " + -// "sk.group_name " + -// "FROM enrollment_table e " + -// "JOIN attendance a ON e.enrollment_id = a.enrollment_id " + -// "LEFT JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " + -// "LEFT JOIN suyaudavi_kuzhu sk ON e.group_id = sk.group_id " + -// "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) "); -// -// // Check if incharge_id is present -// sql.append("AND (? IS NULL OR e.incharge_id = ?) "); -// -// // Check if month is provided -// if (month != null && !month.isEmpty()) { -// sql.append("AND MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = ? "); -// } -// -// // Check if year is provided -// if (year != null) { -// sql.append("AND YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = ? "); -// } -// -// // Updated GROUP BY to include all non-aggregated columns -// sql.append("GROUP BY e.enrollment_id, e.emp_id, e.name, e.incharge_id, " + -// "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + -// "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + -// "sd.salary_status, sk.group_id, sk.group_name"); -// -// // Create a list of parameters -// List params = new ArrayList<>(); -// params.add(incharge_id); -// params.add(incharge_id); // Added twice for the conditional check in the SQL -// if (month != null && !month.isEmpty()) { -// params.add(month); -// } -// if (year != null) { -// params.add(year); -// } -// -// // Log SQL and parameters -// System.out.println("Generated SQL: " + sql.toString()); -// System.out.println("Parameters: " + params); -// -// // Execute the query -// List> results = jdbcTemplate.queryForList(sql.toString(), params.toArray()); -// return results; -// } + + /************************************** + * Updated code working 08-10-2024 + ******************************************/ + // public List> getAttendanceWithSalaryByInchargeId(String + // month, Integer year, Integer incharge_id) { + // StringBuilder sql = new StringBuilder("SELECT " + + // "e.group_id, " + + // "(SELECT group_name FROM suyaudavi_kuzhu WHERE suyaudavi_kuzhu.group_id = + // e.group_id LIMIT 1) AS group_name, " + + // "a.enrollment_id, " + + // "e.emp_id, " + + // "e.name, " + + // "e.incharge_id, " + + // "e.incharge_name, " + + // "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id + // DESC LIMIT 1) AS salary_per_day, " + + // "(SELECT wage_id FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC + // LIMIT 1) AS wage_id, " + + // "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS year, " + + // "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS month, " + // + + // "DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime))) AS + // total_days, " + + // "COUNT(DISTINCT DATE(a.indatetime)) AS total_days_present, " + + // "COUNT(DISTINCT DATE(a.oddatetime)) AS total_days_od, " + + // "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) AS + // total_days_salary, " + + // "((COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) * + // " + + // "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id + // DESC LIMIT 1)) AS total_salary, " + + // "(MAX(DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)))) - + // " + + // "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime)))) + // AS total_days_absent, " + + // "IFNULL(s.salary_status, '') AS salary_status " + + // "FROM attendance AS a " + + // "INNER JOIN enrollment_table AS e ON a.enrollment_id = e.enrollment_id " + + // "LEFT JOIN salary_details AS s ON a.enrollment_id = s.enrollment_id " + + // "AND s.month = MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, + // a.oddatetime)) " + + // "AND s.year = YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) " + + // "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) + // "); + // + // // Append condition for incharge_id + // sql.append("AND (? IS NULL OR e.incharge_id = ?) "); + // + // // Append condition for month if provided + // if (month != null && !month.isEmpty()) { + // sql.append("AND MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, + // a.oddatetime)) = ? "); + // } + // + // // Append condition for year if provided + // if (year != null) { + // sql.append("AND YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = + // ? "); + // } + // + // // Group by necessary columns + // sql.append("GROUP BY a.enrollment_id, e.group_id, " + + // "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + + // "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + + // "(SELECT salary_per_day FROM staff_wages WHERE isactive = 1 ORDER BY wage_id + // DESC LIMIT 1), " + + // "(SELECT wage_id FROM staff_wages WHERE isactive = 1 ORDER BY wage_id DESC + // LIMIT 1), " + + // "(SELECT group_name FROM suyaudavi_kuzhu WHERE suyaudavi_kuzhu.group_id = + // e.group_id LIMIT 1), " + + // "DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime))), " + + // "s.salary_status"); + // + // // Create a list of parameters + // List params = new ArrayList<>(); + // params.add(incharge_id); + // params.add(incharge_id); // Added twice for the conditional check in the SQL + // if (month != null && !month.isEmpty()) { + // params.add(month); + // } + // if (year != null) { + // params.add(year); + // } + // + // // Log the SQL and parameters (optional for debugging) + // System.out.println("Generated SQL: " + sql.toString()); + // System.out.println("Parameters: " + params); + // + // // Execute the query using JdbcTemplate + // List> results = jdbcTemplate.queryForList(sql.toString(), + // params.toArray()); + // return results; + // } + + // public List> getAttendanceWithSalaryByInchargeId(String + // month, Integer year, Integer incharge_id) { + // StringBuilder sql = new StringBuilder("SELECT " + + // "e.enrollment_id, " + + // "e.emp_id, " + + // "e.name, " + + // "e.incharge_id, " + + // "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS year, " + + // "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS month, " + // + + // "COUNT(DISTINCT DATE(a.indatetime)) AS total_days_present, " + + // "COUNT(DISTINCT DATE(a.oddatetime)) AS total_days_od, " + + // "MAX(DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)))) AS + // total_days, " + + // "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) AS + // total_days_salary, " + + // "(MAX(DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)))) - + // " + + // "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime)))) + // AS total_days_absent, " + + // "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY + // sw.effect_from_date DESC LIMIT 1) AS salary_per_day, " + + // "((COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) * + // " + + // "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY + // sw.effect_from_date DESC LIMIT 1)) AS total_salary, " + + // "IFNULL(sd.salary_status, '') AS salary_status, " + // Modified salary_status + // to return an empty string + // "sk.group_id, " + + // "sk.group_name " + + // "FROM enrollment_table e " + + // "JOIN attendance a ON e.enrollment_id = a.enrollment_id " + + // "LEFT JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " + + // "LEFT JOIN suyaudavi_kuzhu sk ON e.group_id = sk.group_id " + + // "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) + // "); + // + // // Check if incharge_id is present + // sql.append("AND (? IS NULL OR e.incharge_id = ?) "); + // + // // Check if month is provided + // if (month != null && !month.isEmpty()) { + // sql.append("AND MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, + // a.oddatetime)) = ? "); + // } + // + // // Check if year is provided + // if (year != null) { + // sql.append("AND YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = + // ? "); + // } + // + // // Updated GROUP BY to include all non-aggregated columns + // sql.append("GROUP BY e.enrollment_id, e.emp_id, e.name, e.incharge_id, " + + // "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + + // "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), " + + // "sd.salary_status, sk.group_id, sk.group_name"); + // + // // Create a list of parameters + // List params = new ArrayList<>(); + // params.add(incharge_id); + // params.add(incharge_id); // Added twice for the conditional check in the SQL + // if (month != null && !month.isEmpty()) { + // params.add(month); + // } + // if (year != null) { + // params.add(year); + // } + // + // // Log SQL and parameters + // System.out.println("Generated SQL: " + sql.toString()); + // System.out.println("Parameters: " + params); + // + // // Execute the query + // List> results = jdbcTemplate.queryForList(sql.toString(), + // params.toArray()); + // return results; + // } /* - public List> getAttendanceWithSalaryByInchargeId(String month, Integer year, Integer incharge_id) { - - StringBuilder sql = new StringBuilder("SELECT " + - "e.enrollment_id, " + - "e.emp_id, " + - "e.name, " + - "e.incharge_id, " + - "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS year, " + - "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS month, " + - "COUNT(DISTINCT DATE(a.indatetime)) AS total_days_present, " + - "COUNT(DISTINCT DATE(a.leavedatetime)) AS total_days_absent, " + - "COUNT(DISTINCT DATE(a.oddatetime)) AS total_days_od, " + - "DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime))) AS total_days, " + - "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) AS total_days_salary, " + - "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1) AS salary_per_day, " + - "((COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) * " + - "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1)) AS total_salary, " + - "COALESCE(sd.salary_status, '') AS salary_status, COALESCE(sk.group_id, '') AS group_id, " + - "COALESCE(sk.group_name, '') AS group_name " + - "FROM enrollment_table e " + - "JOIN attendance a ON e.enrollment_id = a.enrollment_id " + - "LEFT JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " + - "LEFT JOIN suyaudavi_kuzhu sk ON e.group_id = sk.group_id " + - "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) "); - - // Check if incharge_id is present - sql.append("AND (? IS NULL OR e.incharge_id = ?) "); - - // Check if month is provided - if (month != null && !month.isEmpty()) { - sql.append("AND MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = ? "); - } - - // Check if year is provided - if (year != null) { - sql.append("AND YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = ? "); - } - - sql.append("GROUP BY e.enrollment_id, e.name, YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), total_days, sd.salary_status, sk.group_id, sk.group_name"); - - // Create a list of parameters - List params = new ArrayList<>(); - params.add(incharge_id); - params.add(incharge_id); // Added twice for the conditional check in the SQL - if (month != null && !month.isEmpty()) { - params.add(month); - } - if (year != null) { - params.add(year); - } - - // Log SQL and parameters - System.out.println("Generated SQL: " + sql.toString()); - System.out.println("Parameters: " + params); - - // Execute the query - List> results = jdbcTemplate.queryForList(sql.toString(), params.toArray()); - return results; - } - */ - - public List> getConsolidatedAttendanceReport(String fromdate, String todate, String groupName, String zone, String division) { // newly added - String sql = "select \n" + - "et.emp_id, et.enrollment_id, et.name, " + - "MAX(DAY(LAST_DAY(COALESCE(att.indatetime, att.leavedatetime, att.oddatetime)))) AS total_days, " + - "count(distinct date(att.indatetime)) as totaldayspresent, " + - "count(distinct case when att.indatetime is null then date(att.oddatetime) end) as totaldaysod, " + - "count(distinct date(att.leavedatetime)) as totaldaysleave, " + - "MAX(DAY(LAST_DAY(COALESCE(att.indatetime, att.leavedatetime, att.oddatetime)))) - " + - "((count(distinct date(att.indatetime)) + " + - "count(distinct case when att.indatetime is null then date(att.oddatetime) end) + " + - "count(distinct date(att.leavedatetime)))) as totaldaysabsent, " + - "et.incharge_name, et.incharge_phoneno, et.incharge_designation, et.zone, " + - "et.division, et.department, sk.group_name from attendance att " - + " left join enrollment_table et on att.enrollment_id = et.enrollment_id " - + " left join suyaudavi_kuzhu sk on et.group_id = sk.group_id where " - + " (DATE(att.indatetime) BETWEEN STR_TO_DATE('" + fromdate + "', '%Y-%m-%d') AND STR_TO_DATE('" + todate + "', '%Y-%m-%d') " - + " OR DATE(att.oddatetime) BETWEEN STR_TO_DATE('" + fromdate + "', '%Y-%m-%d') AND STR_TO_DATE('" + todate + "', '%Y-%m-%d')" - + " OR DATE(att.leavedatetime) BETWEEN STR_TO_DATE('" + fromdate + "', '%Y-%m-%d') AND STR_TO_DATE('" + todate + "', '%Y-%m-%d')) " - + (zone != null && !zone.isEmpty() ? " and et.zone = ? " : "") - + (division != null && !division.isEmpty() ? " and et.division = ? " : "") - + (groupName != null && !groupName.isEmpty() ? " and sk.group_name = ? " : "") - + " group by et.emp_id, et.enrollment_id, et.name, et.incharge_name, et.incharge_phoneno, et.incharge_designation, et.zone, " - + " et.division, et.department, sk.group_name"; - - // Prepare the query parameters based on provided inputs - List params = new ArrayList<>(); - //params.add(fromdate); - //params.add(todate); - if (groupName != null && !groupName.isEmpty()) { - params.add(groupName); - } - if (zone != null && !zone.isEmpty()) { - params.add(zone); - } - if (division != null && !division.isEmpty()) { - params.add(division); - } - - - List> results = jdbcTemplate.queryForList(sql.toString(), params.toArray()); - return results; - } - - -public Map> fetchAttendanceDates(String enrollmentId, String fromdate, String todate, String type) { //newly added - Map> attendanceData = new HashMap<>(); - - if (type.equals("present")) { - String presentQuery = "SELECT DISTINCT DATE_FORMAT(DATE(indatetime), '%d-%m-%Y') AS PresentDates " + - "FROM attendance WHERE enrollment_id = ? AND DATE(indatetime) BETWEEN STR_TO_DATE(? , '%Y-%m-%d') AND " + - "STR_TO_DATE(? , '%Y-%m-%d')"; - attendanceData.put("presentDates", jdbcTemplate.queryForList(presentQuery, String.class, enrollmentId, fromdate, todate)); - - } else if (type.equals("od")) { - String odQuery = "SELECT DISTINCT DATE_FORMAT(DATE(oddatetime), '%d-%m-%Y') AS OdDates " + - "FROM attendance WHERE enrollment_id = ? AND DATE(oddatetime) BETWEEN STR_TO_DATE(?, '%Y-%m-%d') AND STR_TO_DATE(?, '%Y-%m-%d')"; - attendanceData.put("odDates", jdbcTemplate.queryForList(odQuery, String.class, enrollmentId, fromdate, todate)); - } else if (type.equals("leave")) { - String leaveQuery = "SELECT DISTINCT DATE_FORMAT(DATE(leavedatetime), '%d-%m-%Y') AS LeaveDates " + - "FROM attendance WHERE enrollment_id = ? AND DATE(leavedatetime) BETWEEN STR_TO_DATE(?, '%Y-%m-%d') AND STR_TO_DATE(?, '%Y-%m-%d')"; - attendanceData.put("leaveDates", jdbcTemplate.queryForList(leaveQuery, String.class, enrollmentId, fromdate, todate)); - } else if (type.equals("absent")) { - String absentQuery = ""; - - } - - return attendanceData; - } + * public List> getAttendanceWithSalaryByInchargeId(String + * month, Integer year, Integer incharge_id) { + * + * StringBuilder sql = new StringBuilder("SELECT " + + * "e.enrollment_id, " + + * "e.emp_id, " + + * "e.name, " + + * "e.incharge_id, " + + * "YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS year, " + + * "MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) AS month, " + * + + * "COUNT(DISTINCT DATE(a.indatetime)) AS total_days_present, " + + * "COUNT(DISTINCT DATE(a.leavedatetime)) AS total_days_absent, " + + * "COUNT(DISTINCT DATE(a.oddatetime)) AS total_days_od, " + + * "DAY(LAST_DAY(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime))) AS total_days, " + * + + * "(COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) AS total_days_salary, " + * + + * "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1) AS salary_per_day, " + * + + * "((COUNT(DISTINCT DATE(a.indatetime)) + COUNT(DISTINCT DATE(a.oddatetime))) * " + * + + * "(SELECT sw.salary_per_day FROM staff_wages sw WHERE sw.isactive = 1 ORDER BY sw.effect_from_date DESC LIMIT 1)) AS total_salary, " + * + + * "COALESCE(sd.salary_status, '') AS salary_status, COALESCE(sk.group_id, '') AS group_id, " + * + + * "COALESCE(sk.group_name, '') AS group_name " + + * "FROM enrollment_table e " + + * "JOIN attendance a ON e.enrollment_id = a.enrollment_id " + + * "LEFT JOIN salary_details sd ON e.enrollment_id = sd.enrollment_id " + + * "LEFT JOIN suyaudavi_kuzhu sk ON e.group_id = sk.group_id " + + * "WHERE (a.inby IS NOT NULL OR a.leaveby IS NOT NULL OR a.odby IS NOT NULL) " + * ); + * + * // Check if incharge_id is present + * sql.append("AND (? IS NULL OR e.incharge_id = ?) "); + * + * // Check if month is provided + * if (month != null && !month.isEmpty()) { + * sql. + * append("AND MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = ? " + * ); + * } + * + * // Check if year is provided + * if (year != null) { + * sql. + * append("AND YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)) = ? " + * ); + * } + * + * sql. + * append("GROUP BY e.enrollment_id, e.name, YEAR(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), MONTHNAME(COALESCE(a.indatetime, a.leavedatetime, a.oddatetime)), total_days, sd.salary_status, sk.group_id, sk.group_name" + * ); + * + * // Create a list of parameters + * List params = new ArrayList<>(); + * params.add(incharge_id); + * params.add(incharge_id); // Added twice for the conditional check in the SQL + * if (month != null && !month.isEmpty()) { + * params.add(month); + * } + * if (year != null) { + * params.add(year); + * } + * + * // Log SQL and parameters + * System.out.println("Generated SQL: " + sql.toString()); + * System.out.println("Parameters: " + params); + * + * // Execute the query + * List> results = jdbcTemplate.queryForList(sql.toString(), + * params.toArray()); + * return results; + * } + */ + + public List> getConsolidatedAttendanceReport(String fromdate, String todate, String groupName, + String zone, String division) { // newly added + String sql = "select \n" + + "et.emp_id, et.enrollment_id, et.name, " + + "MAX(DAY(LAST_DAY(COALESCE(att.indatetime, att.leavedatetime, att.oddatetime)))) AS total_days, " + + "count(distinct date(att.indatetime)) as totaldayspresent, " + + "count(distinct case when att.indatetime is null then date(att.oddatetime) end) as totaldaysod, " + + "count(distinct date(att.leavedatetime)) as totaldaysleave, " + + "MAX(DAY(LAST_DAY(COALESCE(att.indatetime, att.leavedatetime, att.oddatetime)))) - " + + "((count(distinct date(att.indatetime)) + " + + "count(distinct case when att.indatetime is null then date(att.oddatetime) end) + " + + "count(distinct date(att.leavedatetime)))) as totaldaysabsent, " + + "et.incharge_name, et.incharge_phoneno, et.incharge_designation, et.zone, " + + "et.division, et.department, sk.group_name from attendance att " + + " left join enrollment_table et on att.enrollment_id = et.enrollment_id " + + " left join suyaudavi_kuzhu sk on et.group_id = sk.group_id where " + + " (DATE(att.indatetime) BETWEEN STR_TO_DATE('" + fromdate + "', '%Y-%m-%d') AND STR_TO_DATE('" + + todate + "', '%Y-%m-%d') " + + " OR DATE(att.oddatetime) BETWEEN STR_TO_DATE('" + fromdate + "', '%Y-%m-%d') AND STR_TO_DATE('" + + todate + "', '%Y-%m-%d')" + + " OR DATE(att.leavedatetime) BETWEEN STR_TO_DATE('" + fromdate + "', '%Y-%m-%d') AND STR_TO_DATE('" + + todate + "', '%Y-%m-%d')) " + + (zone != null && !zone.isEmpty() ? " and et.zone = ? " : "") + + (division != null && !division.isEmpty() ? " and et.division = ? " : "") + + (groupName != null && !groupName.isEmpty() ? " and sk.group_name = ? " : "") + + " group by et.emp_id, et.enrollment_id, et.name, et.incharge_name, et.incharge_phoneno, et.incharge_designation, et.zone, " + + " et.division, et.department, sk.group_name"; + // Prepare the query parameters based on provided inputs + List params = new ArrayList<>(); + // params.add(fromdate); + // params.add(todate); + if (groupName != null && !groupName.isEmpty()) { + params.add(groupName); + } + if (zone != null && !zone.isEmpty()) { + params.add(zone); + } + if (division != null && !division.isEmpty()) { + params.add(division); + } + List> results = jdbcTemplate.queryForList(sql.toString(), params.toArray()); + return results; + } - public List> getSelfHelpGroupDetails() { // newly added - String sql = "select * from suyaudavi_kuzhu where isactive = 1 and isdelete =0 order by group_name asc"; - List> results = jdbcTemplate.queryForList(sql); - return results; - } + public Map> fetchAttendanceDates(String enrollmentId, String fromdate, String todate, + String type) { // newly added + Map> attendanceData = new HashMap<>(); + + if (type.equals("present")) { + String presentQuery = "SELECT DISTINCT DATE_FORMAT(DATE(indatetime), '%d-%m-%Y') AS PresentDates " + + "FROM attendance WHERE enrollment_id = ? AND DATE(indatetime) BETWEEN STR_TO_DATE(? , '%Y-%m-%d') AND " + + + "STR_TO_DATE(? , '%Y-%m-%d')"; + attendanceData.put("presentDates", + jdbcTemplate.queryForList(presentQuery, String.class, enrollmentId, fromdate, todate)); + + } else if (type.equals("od")) { + String odQuery = "SELECT DISTINCT DATE_FORMAT(DATE(oddatetime), '%d-%m-%Y') AS OdDates " + + "FROM attendance WHERE enrollment_id = ? AND DATE(oddatetime) BETWEEN STR_TO_DATE(?, '%Y-%m-%d') AND STR_TO_DATE(?, '%Y-%m-%d')"; + attendanceData.put("odDates", + jdbcTemplate.queryForList(odQuery, String.class, enrollmentId, fromdate, todate)); + } else if (type.equals("leave")) { + String leaveQuery = "SELECT DISTINCT DATE_FORMAT(DATE(leavedatetime), '%d-%m-%Y') AS LeaveDates " + + "FROM attendance WHERE enrollment_id = ? AND DATE(leavedatetime) BETWEEN STR_TO_DATE(?, '%Y-%m-%d') AND STR_TO_DATE(?, '%Y-%m-%d')"; + attendanceData.put("leaveDates", + jdbcTemplate.queryForList(leaveQuery, String.class, enrollmentId, fromdate, todate)); + } else if (type.equals("absent")) { + String absentQuery = ""; + } + return attendanceData; + } + + public List> getSelfHelpGroupDetails() { // newly added + String sql = "select * from suyaudavi_kuzhu where isactive = 1 and isdelete =0 order by group_name asc"; + List> results = jdbcTemplate.queryForList(sql); + return results; + } public List> getSalaryNotInitiatedReport(String month, Integer year, String groupName) { - String sql = "SELECT e.emp_id, e.name, e.designation, e.incharge_name, e.incharge_designation, e.incharge_phoneno, sk.group_name " + - "FROM enrollment_table e " + - "left join suyaudavi_kuzhu sk on e.group_id = sk.group_id " + - "WHERE NOT EXISTS ( SELECT 1 " + - " FROM salary_details s " + - " WHERE e.enrollment_id = s.enrollment_id " + - " AND s.month = ? " + - " AND s.year = ? )" - + (groupName != null && !groupName.isEmpty() ? " and sk.group_name = ? " : ""); + String sql = "SELECT e.emp_id, e.name, e.designation, e.incharge_name, e.incharge_designation, e.incharge_phoneno, sk.group_name " + + + "FROM enrollment_table e " + + "left join suyaudavi_kuzhu sk on e.group_id = sk.group_id " + + "WHERE NOT EXISTS ( SELECT 1 " + + " FROM salary_details s " + + " WHERE e.enrollment_id = s.enrollment_id " + + " AND s.month = ? " + + " AND s.year = ? )" + + (groupName != null && !groupName.isEmpty() ? " and sk.group_name = ? " : ""); - List params = new ArrayList<>(); + List params = new ArrayList<>(); + + params.add(month); + params.add(year); - params.add(month); - params.add(year); + if (groupName != null && !groupName.isEmpty()) { + params.add(groupName); + } - if (groupName != null && !groupName.isEmpty()) { - params.add(groupName); - } + return jdbcTemplate.queryForList(sql, params.toArray()); + } - return jdbcTemplate.queryForList(sql, params.toArray()); - } - public boolean checkSalaryDetails(int enrollmentId, String month, int year) { - String sql = "select enrollment_id from salary_details where enrollment_id =? and month = ? and year = ?"; - //boolean result = jdbcTemplate.update(sql, enrollmentId, month, year) == 1; - List results = jdbcTemplate.queryForList(sql, Integer.class, enrollmentId, month, year); - return !results.isEmpty(); - //return result; - } - + String sql = "select enrollment_id from salary_details where enrollment_id =? and month = ? and year = ?"; + // boolean result = jdbcTemplate.update(sql, enrollmentId, month, year) == 1; + List results = jdbcTemplate.queryForList(sql, Integer.class, enrollmentId, month, year); + return !results.isEmpty(); + // return result; + } + public int addSalaryDetails( - int totalDaysPresent, int totalDaysOd, int totalDaysSalary, int totalDaysAbsent, + int totalDaysPresent, int totalDaysOd, int totalDaysSalary, int totalDaysAbsent, String month, int year, int salaryAmount, - String salaryStatus, int enrollmentId, int groupId, int wageId, int inchargeID) { + String salaryStatus, int enrollmentId, int groupId, int wageId, int inchargeID) { String sql = "INSERT INTO salary_details (total_days_present, total_days_od, total_days_salary, total_days_absent, month, year, " - + "salary_amount, salary_status, enrollment_id, group_id, wage_id, incharge_id) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; + + "salary_amount, salary_status, enrollment_id, group_id, wage_id, incharge_id) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - return jdbcTemplate.update(sql, totalDaysPresent, totalDaysOd, totalDaysSalary, totalDaysAbsent, month, year, salaryAmount, salaryStatus, enrollmentId, groupId, wageId, inchargeID); + return jdbcTemplate.update(sql, totalDaysPresent, totalDaysOd, totalDaysSalary, totalDaysAbsent, month, year, + salaryAmount, salaryStatus, enrollmentId, groupId, wageId, inchargeID); } public int updateSalaryDetails( - int totalDaysPresent, int totalDaysOd, int totalDaysSalary, - int totalDaysAbsent, String month, int year, int salaryAmount, - String salaryStatus, int enrollmentId, int groupId, + int totalDaysPresent, int totalDaysOd, int totalDaysSalary, + int totalDaysAbsent, String month, int year, int salaryAmount, + String salaryStatus, int enrollmentId, int groupId, int wageId, int inchargeID) { String sql = "update salary_details set total_days_present =?, total_days_od=?, total_days_salary = ? , total_days_absent = ?, month = ?, year = ?, " + "salary_amount = ?, salary_status = ?, enrollment_id = ?, group_id= ?, wage_id= ?, incharge_id = ? where enrollment_id =? and month = ? and year = ?) "; - return jdbcTemplate.update(sql, totalDaysPresent, totalDaysOd, totalDaysSalary, totalDaysAbsent, month, year, salaryAmount, salaryStatus, enrollmentId, groupId, wageId, inchargeID, enrollmentId, month, year); + return jdbcTemplate.update(sql, totalDaysPresent, totalDaysOd, totalDaysSalary, totalDaysAbsent, month, year, + salaryAmount, salaryStatus, enrollmentId, groupId, wageId, inchargeID, enrollmentId, month, year); } } \ No newline at end of file diff --git a/gcc_officer_portal/src/main/java/in/gov/chennaicorporation/gccoffice/vtrack/service/VehicleService.java b/gcc_officer_portal/src/main/java/in/gov/chennaicorporation/gccoffice/vtrack/service/VehicleService.java index 7fd6a76f..fcd3ce4e 100644 --- a/gcc_officer_portal/src/main/java/in/gov/chennaicorporation/gccoffice/vtrack/service/VehicleService.java +++ b/gcc_officer_portal/src/main/java/in/gov/chennaicorporation/gccoffice/vtrack/service/VehicleService.java @@ -1,4 +1,5 @@ package in.gov.chennaicorporation.gccoffice.vtrack.service; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; @@ -31,626 +32,700 @@ import in.gov.chennaicorporation.gccoffice.controller.DateTimeUtil; @Service public class VehicleService { - + private JdbcTemplate jdbcTemplate; - + private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; - private static final int STRING_LENGTH = 15; - private static final Random RANDOM = new SecureRandom(); - + private static final int STRING_LENGTH = 15; + private static final Random RANDOM = new SecureRandom(); + @Autowired - private Environment environment; + private Environment environment; private String fileBaseUrl; - + @Autowired public VehicleService(Environment environment) { - this.fileBaseUrl=environment.getProperty("fileBaseUrl"); + this.fileBaseUrl = environment.getProperty("fileBaseUrl"); } - + @Autowired public void setDataSource(@Qualifier("mysqlVehiclTrackingDataSource") DataSource dataSource) { this.jdbcTemplate = new JdbcTemplate(dataSource); } - + public static String generateRandomString() { - StringBuilder result = new StringBuilder(STRING_LENGTH); - for (int i = 0; i < STRING_LENGTH; i++) { - result.append(CHARACTERS.charAt(RANDOM.nextInt(CHARACTERS.length()))); - } - return result.toString(); - } - + StringBuilder result = new StringBuilder(STRING_LENGTH); + for (int i = 0; i < STRING_LENGTH; i++) { + result.append(CHARACTERS.charAt(RANDOM.nextInt(CHARACTERS.length()))); + } + return result.toString(); + } + public static String generateRandomStringForFile(int String_Lenth) { - StringBuilder result = new StringBuilder(String_Lenth); - for (int i = 0; i < STRING_LENGTH; i++) { - result.append(CHARACTERS.charAt(RANDOM.nextInt(CHARACTERS.length()))); - } - return result.toString(); - } - + StringBuilder result = new StringBuilder(String_Lenth); + for (int i = 0; i < STRING_LENGTH; i++) { + result.append(CHARACTERS.charAt(RANDOM.nextInt(CHARACTERS.length()))); + } + return result.toString(); + } + private byte[] compressImage(BufferedImage image, float quality) throws IOException { - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(byteArrayOutputStream); + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(byteArrayOutputStream); - ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next(); - writer.setOutput(imageOutputStream); + ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next(); + writer.setOutput(imageOutputStream); - ImageWriteParam param = writer.getDefaultWriteParam(); - if (param.canWriteCompressed()) { - param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); - param.setCompressionQuality(quality); - } + ImageWriteParam param = writer.getDefaultWriteParam(); + if (param.canWriteCompressed()) { + param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); + param.setCompressionQuality(quality); + } - writer.write(null, new javax.imageio.IIOImage(image, null, null), param); + writer.write(null, new javax.imageio.IIOImage(image, null, null), param); - writer.dispose(); - imageOutputStream.close(); + writer.dispose(); + imageOutputStream.close(); + + return byteArrayOutputStream.toByteArray(); + } - return byteArrayOutputStream.toByteArray(); - } - public String fileUpload(String name, String id, MultipartFile file) { - + int lastInsertId = 0; // Set the file path where you want to save it - String uploadDirectory = environment.getProperty("file.upload.directory"); - String serviceFolderName = environment.getProperty("vtrack_foldername"); - var year = DateTimeUtil.getCurrentYear(); - var month = DateTimeUtil.getCurrentMonth(); - var date = DateTimeUtil.getCurrentDay(); - - uploadDirectory = uploadDirectory + serviceFolderName +"/"+ year +"/"+month+"/"+date; - - try { - // Create directory if it doesn't exist - Path directoryPath = Paths.get(uploadDirectory); - if (!Files.exists(directoryPath)) { - Files.createDirectories(directoryPath); - } - - // Datetime string - String datetimetxt = DateTimeUtil.getCurrentDateTime(); - // File name - System.out.println(file.getOriginalFilename()); - String fileName = name+ "_" +id + "_" + datetimetxt + "_" + generateRandomStringForFile(10) + "_" + file.getOriginalFilename(); - fileName = fileName.replaceAll("\\s+", ""); // Remove space on filename - - String filePath = uploadDirectory + "/" + fileName; - - String filepath_txt = "/"+serviceFolderName + "/" + year + "/" + month + "/" + date + "/" + fileName; - - // Create a new Path object - Path path = Paths.get(filePath); - - // Get the bytes of the file - byte[] bytes = file.getBytes(); - - // Compress the image - //BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes)); - //byte[] compressedBytes = compressImage(image, 0.5f); // Compress with 50% quality - - // Write the bytes to the file - Files.write(path, bytes); - - System.out.println(filePath); - return filepath_txt; - - } catch (IOException e) { - e.printStackTrace(); - return "Failed to save file " + file.getOriginalFilename(); - } + String uploadDirectory = environment.getProperty("file.upload.directory"); + String serviceFolderName = environment.getProperty("vtrack_foldername"); + var year = DateTimeUtil.getCurrentYear(); + var month = DateTimeUtil.getCurrentMonth(); + var date = DateTimeUtil.getCurrentDay(); + + uploadDirectory = uploadDirectory + serviceFolderName + "/" + year + "/" + month + "/" + date; + + try { + // Create directory if it doesn't exist + Path directoryPath = Paths.get(uploadDirectory); + if (!Files.exists(directoryPath)) { + Files.createDirectories(directoryPath); + } + + // Datetime string + String datetimetxt = DateTimeUtil.getCurrentDateTime(); + // File name + System.out.println(file.getOriginalFilename()); + String fileName = name + "_" + id + "_" + datetimetxt + "_" + generateRandomStringForFile(10) + "_" + + file.getOriginalFilename(); + fileName = fileName.replaceAll("\\s+", ""); // Remove space on filename + + String filePath = uploadDirectory + "/" + fileName; + + String filepath_txt = "/" + serviceFolderName + "/" + year + "/" + month + "/" + date + "/" + fileName; + + // Create a new Path object + Path path = Paths.get(filePath); + + // Get the bytes of the file + byte[] bytes = file.getBytes(); + + // Compress the image + // BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes)); + // byte[] compressedBytes = compressImage(image, 0.5f); // Compress with 50% + // quality + + // Write the bytes to the file + Files.write(path, bytes); + + System.out.println(filePath); + return filepath_txt; + + } catch (IOException e) { + e.printStackTrace(); + return "Failed to save file " + file.getOriginalFilename(); + } + } + + public List> getAllTemplateNames() { + String sql = "SELECT `id`, `name` as template_name, `whatsapp_temp_name`, `whatsapp_temp_id` FROM `whatsapp_template` WHERE `isactive`=1 AND `isdelete`=0"; + return jdbcTemplate.queryForList(sql); } - - public List> getAllTemplateNames() { - String sql = "SELECT `id`, `name` as template_name, `whatsapp_temp_name`, `whatsapp_temp_id` FROM `whatsapp_template` WHERE `isactive`=1 AND `isdelete`=0"; - return jdbcTemplate.queryForList(sql); - } - + public int saveMessageDetails(String date, String tempType, String imgPath) { - String sql = "INSERT INTO `message_list` (`msg_date`, `template_type`, `msg_img`) VALUES (?,?,?)"; - int rowsAffected = jdbcTemplate.update(sql, date, tempType, imgPath); - return rowsAffected; - } - - public List> getAllSavedMessages() { - String sql = "SELECT " - + "ml.`id` as msgid, " - + "ml.`msg_date` as msg_date , " - + "DATE_FORMAT(ml.`msg_date`, '%d-%m-%Y') AS msg_temp_event_date, " - + "DATE_FORMAT(ml.`cdate`, '%d-%m-%Y %r') AS createddate, " - + "ml.`msg_img` as msg_img, " - + "CONCAT('"+fileBaseUrl+"/gcc/files', ml.msg_img) AS msg_attachfile, " - + "wt.`name` as template_name, " - + "wt.`id` as template_id " - + "FROM `message_list` ml " - + "JOIN `whatsapp_template` wt ON ml.`template_type`=wt.`id` " - + "WHERE ml.`isactive` = 1 AND ml.`isdelete` = 0"; - return jdbcTemplate.queryForList(sql); - } - - public String sendMessage(String msgid, String datetxt, String fileurl) { - - String sql = "SELECT " - + "ml.`id` as msgid, " - + "DATE_FORMAT(ml.`msg_date`, '%d-%m-%Y') AS msg_temp_event_date, " - + "CONCAT('"+fileBaseUrl+"/gcc/files', ml.msg_img) AS msg_attachfile, " - + "wt.`id` as template_id " - + "FROM `message_list` ml " - + "JOIN `whatsapp_template` wt ON ml.`template_type`=wt.`id` " - + "WHERE ml.`isactive` = 1 AND ml.`isdelete` = 0 AND ml.`id`=?"; - // Fetch the data - List> result = jdbcTemplate.queryForList(sql, msgid); - - // Initialize variables to store the results - String tempid = ""; - String msgDate = ""; - String fileURL = ""; - String sendTo=""; - // Check if the result list is not empty - if (!result.isEmpty()) { - Map row = result.get(0); // Get the first row (assuming id is unique) - - // Extract values from the result map and assign to variables - tempid = String.valueOf(row.get("template_id")); - msgDate = String.valueOf(row.get("msg_temp_event_date")); - fileURL = String.valueOf(row.get("msg_attachfile")); - - sql = "SELECT `id`, `name`, `mobile`, `userid`, `tempids` FROM `send_msg_to` WHERE `isactive` = 1 AND `isdelete` = 0 AND FIND_IN_SET(?, tempids);"; - List> mobileResult = jdbcTemplate.queryForList(sql,tempid); - // Create a StringBuilder to hold the comma-separated mobile numbers - StringBuilder sendToBuilder = new StringBuilder(); - - // Iterate through the mobileResult list and build the sendTo string - for (Map mobileRow : mobileResult) { - String mobile = String.valueOf(mobileRow.get("mobile")); - - // Append the mobile number to the StringBuilder - if (sendToBuilder.length() > 0) { - sendToBuilder.append(","); - } - sendToBuilder.append(mobile); - } - - // Convert StringBuilder to String - sendTo = sendToBuilder.toString(); - - // Now you have the sendTo string with all mobile numbers - System.out.println("Mobile Numbers: " + sendTo); // For debugging, you can print this value - } - - String urlString=""; - - String username="2000233507"; - String password="h2YjFNcJ"; - //String sendTo="9176617754"; //9176617754,8610011680,9360777472,9123565217 - //String msgDate=datetxt; - //String fileURL=fileurl; - - String apikey = "5c995535-6244-11f0-98fc-02c8a5e042bd"; - String from="919445061913"; - switch (tempid) { - case "1": - - System.out.println("TempID is 1 (Vehicle March Out -> officer_test -> 1308878)"); - urlString="https://media.smsgupshup.com/GatewayAPI/rest?" - + "userid="+username - + "&password="+password - + "&send_to="+sendTo - + "&v=1.1" - + "&format=json" - + "&msg_type=IMAGE" - + "&method=SENDMEDIAMESSAGE" - + "&caption=%2AGCC+Vehicle+Monitoring+System%2A%0A%0AZone-wise+vehicle+march-out+details+for+Today%27s+%28"+msgDate+"%29+AM+shift+are+shared+above.%0A%0AFor+further+details%2C+please+click+on+the+button+below." - + "&media_url="+fileURL - + "&isTemplate=true" - + "&footer=GCC+-+IT+Cell" - + "&buttonUrlParam=login.php%3Funame%3Dgcc.admin2024@jtrack.in%26password%3D123456"; - - // urlString ="https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template&apikey="+apikey+"&from="+from+"&to=9444173345&templateid=2784943&url="; - - urlString ="https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" - + "&apikey="+apikey - + "&from="+from - + "&to={{to}}&templateid=2784943" - + "&url="+fileURL - + "&placeholders=Zone%20wise%20vehicle%20march-out%20details"; - break; - case "2": - System.out.println("TempID is 2 (Fule Dip Details -> fuel_dip_details -> 1309072)"); - - urlString="https://media.smsgupshup.com/GatewayAPI/rest?" - + "userid="+username - + "&password="+password - + "&send_to="+sendTo - + "&v=1.1&format=json" - + "&msg_type=IMAGE" - + "&method=SENDMEDIAMESSAGE" - + "&caption=%2AGCC+Vehicle+Monitoring+System%2A%0A%0AYesterday%27s+%28"+msgDate+"%29+Zone+wise+Fuel+Dip+Details+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." - + "&media_url="+fileURL - + "&isTemplate=true&footer=GCC+-+IT+Cell"; - - urlString ="https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" - + "&apikey="+apikey - + "&from="+from - + "&to={{to}}&templateid=2784943" - + "&url="+fileURL - + "&placeholders=Zone%20wise%20Fuel%20Dip%20Details"; - break; - case "3": - System.out.println("TempID is 3 (Late Marchout Details -> late_marchout_details -> 1309075)"); - urlString="https://media.smsgupshup.com/GatewayAPI/rest?" - + "userid="+username - + "&password="+password - + "&send_to="+sendTo - + "&v=1.1&format=json" - + "&msg_type=IMAGE" - + "&method=SENDMEDIAMESSAGE" - + "&caption=%2AGCC+Vehicle+Monitoring+System%2A%0A%0AToday%27s+%28"+msgDate+"%29+Zone-wise+Late+Marchout+Details+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." - + "&media_url="+fileURL - + "&isTemplate=true&footer=GCC+-+IT+Cell"; - - urlString ="https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" - + "&apikey="+apikey - + "&from="+from - + "&to={{to}}&templateid=2784943" - + "&url="+fileURL - + "&placeholders=Zone%20wise%20Late%20Marchout%20Details"; - break; - case "4": - System.out.println("TempID is 4 (LMV Route Deviation Details -> lmv_route_deviation_details -> 1309081)"); - urlString="https://media.smsgupshup.com/GatewayAPI/rest?" - + "userid="+username - + "&password="+password - + "&send_to="+sendTo - + "&v=1.1&format=json" - + "&msg_type=IMAGE" - + "&method=SENDMEDIAMESSAGE" - + "&caption=%2AGCC+Vehicle+Monitoring+System%2A%0A%0AToday%27s+%28"+msgDate+"%29+Zone-wise+Compactors+LMV+Route+Deviation+Details+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." - + "&media_url="+fileURL - + "&isTemplate=true&footer=GCC+-+IT+Cell"; - - urlString ="https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" - + "&apikey="+apikey - + "&from="+from - + "&to={{to}}&templateid=2784943" - + "&url="+fileURL - + "&placeholders=Zone%20wise%20Compactors%20LMV%20Route%20%20Deviation%20Details"; - break; - case "5": - System.out.println("TempID is 5 (HMV Route Deviation Details -> hmv_route_deviation_details -> 1309083)"); - urlString="https://media.smsgupshup.com/GatewayAPI/rest?" - + "userid="+username - + "&password="+password - + "&send_to="+sendTo - + "&v=1.1&format=json" - + "&msg_type=IMAGE" - + "&method=SENDMEDIAMESSAGE" - + "&caption=%2AGCC+Vehicle+Monitoring+System%2A%0A%0AToday%27s+%28"+msgDate+"%29+Zone-wise+Compactors+HMV+Route+Deviation+Details+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." - + "&media_url="+fileURL - + "&isTemplate=true&footer=GCC+-+IT+Cell"; - - urlString ="https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" - + "&apikey="+apikey - + "&from="+from - + "&to={{to}}&templateid=2784943" - + "&url="+fileURL - + "&placeholders=Zone%20wise%20Compactors%20HMV%20Route%20%20Deviation%20Details"; - break; - - case "6": - System.out.println("TempID is 6 (C&D Waste Removal Monitoring -> c_and_d_waste_removal_monitoring -> 1335786)"); - urlString="https://media.smsgupshup.com/GatewayAPI/rest?" - + "userid="+username - + "&password="+password - + "&send_to="+sendTo - + "&v=1.1&format=json" - + "&msg_type=IMAGE" - + "&method=SENDMEDIAMESSAGE" - + "&caption=%2AGCC+C%26D+Waste+Removal+Monitoring%2A%0A%0AToday%27s+%28"+msgDate+"%29+Zone+wise+C%26D+Waste+Removal+Details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." - + "&media_url="+fileURL - + "&isTemplate=true&footer=GCC+-+IT+Cell"; - - urlString ="https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" - + "&apikey="+apikey - + "&from="+from - + "&to={{to}}&templateid=2784943" - + "&url="+fileURL - + "&placeholders=Zone%20wise%20C%26D%20Waste%20Removal%20details"; - break; - - case "7": - System.out.println("TempID is 7 (Enforcement Team Monitoring -> enforcement_team_monitoring -> 1362100)"); - urlString="https://media.smsgupshup.com/GatewayAPI/rest?" - + "userid="+username - + "&password="+password - + "&send_to="+sendTo - + "&v=1.1&format=json" - + "&msg_type=IMAGE" - + "&method=SENDMEDIAMESSAGE" - + "&caption=%2AGCC+Enforcement+Team+Monitoring%2A%0A%0AYesterday%27s+%28"+msgDate+"%29+Zone+wise+Enforcement+Team+activity+details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." - + "&media_url="+fileURL - + "&isTemplate=true&footer=GCC+-+IT+Cell"; - - urlString ="https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" - + "&apikey="+apikey - + "&from="+from - + "&to={{to}}&templateid=2784943" - + "&url="+fileURL - + "&placeholders=Zone%20wise%20Enforcement%20Team%20activity%20details"; - break; - - case "8": - System.out.println("TempID is 8 (Toilets Monitoring -> gcc_toilets_monitoring -> 1475869)"); - urlString="https://media.smsgupshup.com/GatewayAPI/rest?" - + "userid="+username - + "&password="+password - + "&send_to="+sendTo - + "&v=1.1&format=json" - + "&msg_type=IMAGE" - + "&method=SENDMEDIAMESSAGE" - + "&caption=%2AGCC+Toilets+Monitoring%2A%0A%0AToday%27s+%28"+msgDate+"%29+Zone+wise+Toilets+Morning+inspection+details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." - + "&media_url="+fileURL - + "&isTemplate=true&footer=GCC+-+IT+Cell"; - - urlString ="https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" - + "&apikey="+apikey - + "&from="+from - + "&to={{to}}&templateid=2784943" - + "&url="+fileURL - + "&placeholders=Zone%20wise%20Toilets%20Morning%20inspection%20details"; - break; - - case "9": - System.out.println("TempID is 9 (Toilets Monitoring -> gcc_toilets_evening_monitoring -> 1475881)"); - urlString="https://media.smsgupshup.com/GatewayAPI/rest?" - + "userid="+username - + "&password="+password - + "&send_to="+sendTo - + "&v=1.1&format=json" - + "&msg_type=IMAGE" - + "&method=SENDMEDIAMESSAGE" - + "&caption=%2AGCC+Toilets+Monitoring%2A%0A%0AToday%27s+%28"+msgDate+"%29+Zone+wise+Toilets+Evening+inspection+details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." - + "&media_url="+fileURL - + "&isTemplate=true&footer=GCC+-+IT+Cell"; - - urlString ="https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" - + "&apikey="+apikey - + "&from="+from - + "&to={{to}}&templateid=2784943" - + "&url="+fileURL - + "&placeholders=Zone%20wise%20Toilets%20Evening%20inspection%20details"; - break; - - case "10": - System.out.println("TempID is 10 (Bus Shelter Monitoring -> 1508454 - gcc_bus_shelter_monitoring)"); - urlString="https://media.smsgupshup.com/GatewayAPI/rest?" - + "userid="+username - + "&password="+password - + "&send_to="+sendTo - + "&v=1.1&format=json" - + "&msg_type=IMAGE" - + "&method=SENDMEDIAMESSAGE" - + "&caption=%2AGCC+Bus+Shelter+Monitoring%2A%0A%0AToday%27s+%28"+msgDate+"%29+Zone+wise+Bus+Shelter+inspection+details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." - + "&media_url="+fileURL - + "&isTemplate=true&footer=GCC+-+IT+Cell"; - - urlString ="https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" - + "&apikey="+apikey - + "&from="+from - + "&to={{to}}&templateid=2784943" - + "&url="+fileURL - + "&placeholders=Zone%20wise%20Bus%20Shelter%20inspection%20details"; - break; - - case "11": - System.out.println("TempID is 11 (Still Catch Pit -> 1566758 - silt_catch_pit_cleaning )"); - urlString="https://media.smsgupshup.com/GatewayAPI/rest?" - + "userid="+username - + "&password="+password - + "&send_to="+sendTo - + "&v=1.1&format=json" - + "&msg_type=IMAGE" - + "&method=SENDMEDIAMESSAGE" - + "&caption=%2AGCC+Silt+catch+Pit+Cleaning%2A%0A%0AToday%27s+%28"+msgDate+"%29+Zone+wise+Silt+Catch+Pit+cleaning+details+shared+above+for+your+reference%0A%0AFor+more+details%2C+please+click+the+link+below." - + "&media_url="+fileURL - + "&isTemplate=true&footer=GCC+-+IT+Cell"; - - urlString ="https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" - + "&apikey="+apikey - + "&from="+from - + "&to={{to}}&templateid=2784943" - + "&url="+fileURL - + "&placeholders=Zone%20wise%20Silt%20Catch%20Pit%20cleaning%20details"; - break; - - case "12": - System.out.println("TempID is 12 (1590940 - tree_planting_gcc - IMAGE - STATIC)"); - urlString="https://media.smsgupshup.com/GatewayAPI/rest?" - + "userid="+username - + "&password="+password - + "&send_to="+sendTo - + "&v=1.1&format=json" - + "&msg_type=IMAGE" - + "&method=SENDMEDIAMESSAGE" - + "&caption=%2AGCC+Tree+Planting%2A%0A%0AToday%27s+%28"+msgDate+"%29+Zone+wise+tree+planting+details+shared+above+for+your+reference%0A%0AFor+more+details%2C+please+click+the+link+below." - + "&media_url="+fileURL - + "&isTemplate=true&footer=GCC+-+IT+Cell"; - - urlString ="https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" - + "&apikey="+apikey - + "&from="+from - + "&to={{to}}&templateid=2784943" - + "&url="+fileURL - + "&placeholders=Zone%20wise%20tree%20planting%20details"; - break; - - case "13": - System.out.println("TempID is 13 (1590940 - Chennai Schools (userd of Com Temp ) - IMAGE - STATIC)"); - urlString="https://media.smsgupshup.com/GatewayAPI/rest?" - + "userid="+username - + "&password="+password - + "&send_to="+sendTo - + "&v=1.1&format=json" - + "&msg_type=IMAGE" - + "&method=SENDMEDIAMESSAGE" - //+ "&caption=%2AGCC+The+Chennai+School%2A%0A%0AToday%27s+%28"+msgDate+"%29+Zone+wise+Students+Aadhar+linked+details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." - + "&caption=%2AGCC+The+Chennai+School%2A%0A%0AToday%27s+%28"+msgDate+"%29+Zone+wise+Students+Aadhar+linked+details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." - + "&media_url="+fileURL - + "&isTemplate=true&footer=GCC+-+IT+Cell"; - - urlString ="https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" - + "&apikey="+apikey - + "&from="+from - + "&to={{to}}&templateid=2784943" - + "&url="+fileURL - + "&placeholders=Zone%20wise%20Students%20Aadhar%20linked%20details"; - break; - - case "14": - System.out.println("TempID is 14 (1943196 - pet_wp_report - IMAGE - STATIC)"); - urlString="https://media.smsgupshup.com/GatewayAPI/rest?" - + "userid="+username - + "&password="+password - + "&send_to="+sendTo - + "&v=1.1&format=json" - + "&msg_type=IMAGE" - + "&method=SENDMEDIAMESSAGE" - //+ "&caption=%2AGCC+The+Chennai+School%2A%0A%0AToday%27s+%28"+msgDate+"%29+Zone+wise+Students+Aadhar+linked+details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." - + "&caption=%2AGCC+PET+LICENSE+%26+VACCINATION%2A%0A%0AToday%27s+%28"+msgDate+"%29+Zone+wise+Pet+license+%26+Vaccination+details+shared+above+for+your+kind+reference." - + "&media_url="+fileURL - + "&isTemplate=true&footer=GCC+-+IT+Cell"; - - urlString ="https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" - + "&apikey="+apikey - + "&from="+from - + "&to={{to}}&templateid=2784943" - + "&url="+fileURL - + "&placeholders=Zone%20wise%20Pet%20license%20%26%20Vaccination%20details"; - break; - - case "15": - System.out.println("TempID is 15 (1590940 - GCC POS Penalty Monitoring Zone (userd of Com Temp ) - IMAGE - STATIC)"); - urlString="https://media.smsgupshup.com/GatewayAPI/rest?" - + "userid="+username - + "&password="+password - + "&send_to="+sendTo - + "&v=1.1&format=json" - + "&msg_type=IMAGE" - + "&method=SENDMEDIAMESSAGE" - + "&caption=%2AGCC+POS+Penalty+Monitoring%2A%0A%0AToday%27s+%28"+msgDate+"%29++POS+Penalty+Zone+wise+details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." - + "&media_url="+fileURL - + "&isTemplate=true&footer=GCC+-+IT+Cell"; - - urlString ="https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" - + "&apikey="+apikey - + "&from="+from - + "&to={{to}}&templateid=2784943" - + "&url="+fileURL - + "&placeholders=POS%20Penalty%20Zone%20wise%20details"; - - break; - - case "16": - System.out.println("TempID is 16 (1590940 - GCC POS Penalty Monitoring Catagory (userd of Com Temp ) - IMAGE - STATIC)"); - urlString="https://media.smsgupshup.com/GatewayAPI/rest?" - + "userid="+username - + "&password="+password - + "&send_to="+sendTo - + "&v=1.1&format=json" - + "&msg_type=IMAGE" - + "&method=SENDMEDIAMESSAGE" - + "&caption=%2AGCC+POS+Penalty+Monitoring%2A%0A%0AToday%27s+%28"+msgDate+"%29++POS+Penalty+Catagory+wise+details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." - + "&media_url="+fileURL - + "&isTemplate=true&footer=GCC+-+IT+Cell"; - - urlString ="https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" - + "&apikey="+apikey - + "&from="+from - + "&to={{to}}&templateid=2784943" - + "&url="+fileURL - + "&placeholders=POS%20Penalty%20Catagory%20wise%20details"; - break; - - case "17": - System.out.println("TempID is 17 (1590940 - GCC Enforcement Team Monitoring Temp (userd of Com Temp ) - IMAGE - STATIC)"); - urlString="https://media.smsgupshup.com/GatewayAPI/rest?" - + "userid="+username - + "&password="+password - + "&send_to="+sendTo - + "&v=1.1&format=json" - + "&msg_type=IMAGE" - + "&method=SENDMEDIAMESSAGE" - + "&caption=%2AGCC+Enforcement+Team+Monitoring%2A%0A%0AToday%27s+%28"+msgDate+"%29+Zone+wise+Enforcement+Team+activity+details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." - + "&media_url="+fileURL - + "&isTemplate=true&footer=GCC+-+IT+Cell"; - - urlString ="https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" - + "&apikey="+apikey - + "&from="+from - + "&to={{to}}&templateid=2784943" - + "&url="+fileURL - + "&placeholders=Zone%20wise%20Enforcement%20Team%20activity%20details"; - - - - break; - - default: - System.out.println("TempID ("+tempid+") is unknown"); - } - - if (!urlString.isBlank()) { - sql = "SELECT `id`, `name`, `mobile`, `userid`, `tempids` FROM `send_msg_to` WHERE `isactive` = 1 AND `isdelete` = 0 AND FIND_IN_SET(?, tempids);"; - List> mobileResult2 = jdbcTemplate.queryForList(sql,tempid); - for (Map mobileRow2 : mobileResult2) { - String mobile = String.valueOf(mobileRow2.get("mobile")); - String finalUrl = urlString.replace("{{to}}", mobile); - String response = sendWhatsAppMessage(finalUrl); - System.out.println("WhatsApp response: " + response); - } - } - - return "success"; - } - - private String sendWhatsAppMessage(String urlString) { - String response = ""; - try { - URL url = new URL(urlString); - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - connection.setRequestMethod("GET"); - - int responseCode = connection.getResponseCode(); - response = String.valueOf(responseCode); - System.out.println("Response Code for URL: " + urlString + " is " + responseCode); - - } catch (Exception e) { - e.printStackTrace(); - } - return response; - } - - public String disablemessage(String msgid) { - String sql = "update message_list set isdelete =1, isactive = 0 where id = ?"; + String sql = "INSERT INTO `message_list` (`msg_date`, `template_type`, `msg_img`) VALUES (?,?,?)"; + int rowsAffected = jdbcTemplate.update(sql, date, tempType, imgPath); + return rowsAffected; + } + + public List> getAllSavedMessages() { + String sql = "SELECT " + + "ml.`id` as msgid, " + + "ml.`msg_date` as msg_date , " + + "DATE_FORMAT(ml.`msg_date`, '%d-%m-%Y') AS msg_temp_event_date, " + + "DATE_FORMAT(ml.`cdate`, '%d-%m-%Y %r') AS createddate, " + + "ml.`msg_img` as msg_img, " + + "CONCAT('" + fileBaseUrl + "/gcc/files', ml.msg_img) AS msg_attachfile, " + + "wt.`name` as template_name, " + + "wt.`id` as template_id " + + "FROM `message_list` ml " + + "JOIN `whatsapp_template` wt ON ml.`template_type`=wt.`id` " + + "WHERE ml.`isactive` = 1 AND ml.`isdelete` = 0"; + return jdbcTemplate.queryForList(sql); + } + + public String sendMessage(String msgid, String datetxt, String fileurl) { + + String sql = "SELECT " + + "ml.`id` as msgid, " + + "DATE_FORMAT(ml.`msg_date`, '%d-%m-%Y') AS msg_temp_event_date, " + + "CONCAT('" + fileBaseUrl + "/gcc/files', ml.msg_img) AS msg_attachfile, " + + "wt.`id` as template_id " + + "FROM `message_list` ml " + + "JOIN `whatsapp_template` wt ON ml.`template_type`=wt.`id` " + + "WHERE ml.`isactive` = 1 AND ml.`isdelete` = 0 AND ml.`id`=?"; + // Fetch the data + List> result = jdbcTemplate.queryForList(sql, msgid); + + // Initialize variables to store the results + String tempid = ""; + String msgDate = ""; + String fileURL = ""; + String sendTo = ""; + // Check if the result list is not empty + if (!result.isEmpty()) { + Map row = result.get(0); // Get the first row (assuming id is unique) + + // Extract values from the result map and assign to variables + tempid = String.valueOf(row.get("template_id")); + msgDate = String.valueOf(row.get("msg_temp_event_date")); + fileURL = String.valueOf(row.get("msg_attachfile")); + + sql = "SELECT `id`, `name`, `mobile`, `userid`, `tempids` FROM `send_msg_to` WHERE `isactive` = 1 AND `isdelete` = 0 AND FIND_IN_SET(?, tempids);"; + List> mobileResult = jdbcTemplate.queryForList(sql, tempid); + // Create a StringBuilder to hold the comma-separated mobile numbers + StringBuilder sendToBuilder = new StringBuilder(); + + // Iterate through the mobileResult list and build the sendTo string + for (Map mobileRow : mobileResult) { + String mobile = String.valueOf(mobileRow.get("mobile")); + + // Append the mobile number to the StringBuilder + if (sendToBuilder.length() > 0) { + sendToBuilder.append(","); + } + sendToBuilder.append(mobile); + } + + // Convert StringBuilder to String + sendTo = sendToBuilder.toString(); + + // Now you have the sendTo string with all mobile numbers + System.out.println("Mobile Numbers: " + sendTo); // For debugging, you can print this value + } + + String urlString = ""; + + String username = "2000233507"; + String password = "h2YjFNcJ"; + // String sendTo="9176617754"; //9176617754,8610011680,9360777472,9123565217 + // String msgDate=datetxt; + // String fileURL=fileurl; + + String apikey = "5c995535-6244-11f0-98fc-02c8a5e042bd"; + String from = "919445061913"; + switch (tempid) { + case "1": + + System.out.println("TempID is 1 (Vehicle March Out -> officer_test -> 1308878)"); + urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" + + "userid=" + username + + "&password=" + password + + "&send_to=" + sendTo + + "&v=1.1" + + "&format=json" + + "&msg_type=IMAGE" + + "&method=SENDMEDIAMESSAGE" + + "&caption=%2AGCC+Vehicle+Monitoring+System%2A%0A%0AZone-wise+vehicle+march-out+details+for+Today%27s+%28" + + msgDate + + "%29+AM+shift+are+shared+above.%0A%0AFor+further+details%2C+please+click+on+the+button+below." + + "&media_url=" + fileURL + + "&isTemplate=true" + + "&footer=GCC+-+IT+Cell" + + "&buttonUrlParam=login.php%3Funame%3Dgcc.admin2024@jtrack.in%26password%3D123456"; + + // urlString + // ="https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template&apikey="+apikey+"&from="+from+"&to=9444173345&templateid=2784943&url="; + + urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" + + "&apikey=" + apikey + + "&from=" + from + + "&to={{to}}&templateid=2784943" + + "&url=" + fileURL + + "&placeholders=Zone%20wise%20vehicle%20march-out%20details"; + break; + case "2": + System.out.println("TempID is 2 (Fule Dip Details -> fuel_dip_details -> 1309072)"); + + urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" + + "userid=" + username + + "&password=" + password + + "&send_to=" + sendTo + + "&v=1.1&format=json" + + "&msg_type=IMAGE" + + "&method=SENDMEDIAMESSAGE" + + "&caption=%2AGCC+Vehicle+Monitoring+System%2A%0A%0AYesterday%27s+%28" + msgDate + + "%29+Zone+wise+Fuel+Dip+Details+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." + + "&media_url=" + fileURL + + "&isTemplate=true&footer=GCC+-+IT+Cell"; + + urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" + + "&apikey=" + apikey + + "&from=" + from + + "&to={{to}}&templateid=2784943" + + "&url=" + fileURL + + "&placeholders=Zone%20wise%20Fuel%20Dip%20Details"; + break; + case "3": + System.out.println("TempID is 3 (Late Marchout Details -> late_marchout_details -> 1309075)"); + urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" + + "userid=" + username + + "&password=" + password + + "&send_to=" + sendTo + + "&v=1.1&format=json" + + "&msg_type=IMAGE" + + "&method=SENDMEDIAMESSAGE" + + "&caption=%2AGCC+Vehicle+Monitoring+System%2A%0A%0AToday%27s+%28" + msgDate + + "%29+Zone-wise+Late+Marchout+Details+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." + + "&media_url=" + fileURL + + "&isTemplate=true&footer=GCC+-+IT+Cell"; + + urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" + + "&apikey=" + apikey + + "&from=" + from + + "&to={{to}}&templateid=2784943" + + "&url=" + fileURL + + "&placeholders=Zone%20wise%20Late%20Marchout%20Details"; + break; + case "4": + System.out + .println("TempID is 4 (LMV Route Deviation Details -> lmv_route_deviation_details -> 1309081)"); + urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" + + "userid=" + username + + "&password=" + password + + "&send_to=" + sendTo + + "&v=1.1&format=json" + + "&msg_type=IMAGE" + + "&method=SENDMEDIAMESSAGE" + + "&caption=%2AGCC+Vehicle+Monitoring+System%2A%0A%0AToday%27s+%28" + msgDate + + "%29+Zone-wise+Compactors+LMV+Route+Deviation+Details+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." + + "&media_url=" + fileURL + + "&isTemplate=true&footer=GCC+-+IT+Cell"; + + urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" + + "&apikey=" + apikey + + "&from=" + from + + "&to={{to}}&templateid=2784943" + + "&url=" + fileURL + + "&placeholders=Zone%20wise%20Compactors%20LMV%20Route%20%20Deviation%20Details"; + break; + case "5": + System.out + .println("TempID is 5 (HMV Route Deviation Details -> hmv_route_deviation_details -> 1309083)"); + urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" + + "userid=" + username + + "&password=" + password + + "&send_to=" + sendTo + + "&v=1.1&format=json" + + "&msg_type=IMAGE" + + "&method=SENDMEDIAMESSAGE" + + "&caption=%2AGCC+Vehicle+Monitoring+System%2A%0A%0AToday%27s+%28" + msgDate + + "%29+Zone-wise+Compactors+HMV+Route+Deviation+Details+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." + + "&media_url=" + fileURL + + "&isTemplate=true&footer=GCC+-+IT+Cell"; + + urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" + + "&apikey=" + apikey + + "&from=" + from + + "&to={{to}}&templateid=2784943" + + "&url=" + fileURL + + "&placeholders=Zone%20wise%20Compactors%20HMV%20Route%20%20Deviation%20Details"; + break; + + case "6": + System.out.println( + "TempID is 6 (C&D Waste Removal Monitoring -> c_and_d_waste_removal_monitoring -> 1335786)"); + urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" + + "userid=" + username + + "&password=" + password + + "&send_to=" + sendTo + + "&v=1.1&format=json" + + "&msg_type=IMAGE" + + "&method=SENDMEDIAMESSAGE" + + "&caption=%2AGCC+C%26D+Waste+Removal+Monitoring%2A%0A%0AToday%27s+%28" + msgDate + + "%29+Zone+wise+C%26D+Waste+Removal+Details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." + + "&media_url=" + fileURL + + "&isTemplate=true&footer=GCC+-+IT+Cell"; + + urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" + + "&apikey=" + apikey + + "&from=" + from + + "&to={{to}}&templateid=2784943" + + "&url=" + fileURL + + "&placeholders=Zone%20wise%20C%26D%20Waste%20Removal%20details"; + break; + + case "7": + System.out + .println("TempID is 7 (Enforcement Team Monitoring -> enforcement_team_monitoring -> 1362100)"); + urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" + + "userid=" + username + + "&password=" + password + + "&send_to=" + sendTo + + "&v=1.1&format=json" + + "&msg_type=IMAGE" + + "&method=SENDMEDIAMESSAGE" + + "&caption=%2AGCC+Enforcement+Team+Monitoring%2A%0A%0AYesterday%27s+%28" + msgDate + + "%29+Zone+wise+Enforcement+Team+activity+details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." + + "&media_url=" + fileURL + + "&isTemplate=true&footer=GCC+-+IT+Cell"; + + urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" + + "&apikey=" + apikey + + "&from=" + from + + "&to={{to}}&templateid=2784943" + + "&url=" + fileURL + + "&placeholders=Zone%20wise%20Enforcement%20Team%20activity%20details"; + break; + + case "8": + System.out.println("TempID is 8 (Toilets Monitoring -> gcc_toilets_monitoring -> 1475869)"); + urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" + + "userid=" + username + + "&password=" + password + + "&send_to=" + sendTo + + "&v=1.1&format=json" + + "&msg_type=IMAGE" + + "&method=SENDMEDIAMESSAGE" + + "&caption=%2AGCC+Toilets+Monitoring%2A%0A%0AToday%27s+%28" + msgDate + + "%29+Zone+wise+Toilets+Morning+inspection+details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." + + "&media_url=" + fileURL + + "&isTemplate=true&footer=GCC+-+IT+Cell"; + + urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" + + "&apikey=" + apikey + + "&from=" + from + + "&to={{to}}&templateid=2784943" + + "&url=" + fileURL + + "&placeholders=Zone%20wise%20Toilets%20Morning%20inspection%20details"; + break; + + case "9": + System.out.println("TempID is 9 (Toilets Monitoring -> gcc_toilets_evening_monitoring -> 1475881)"); + urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" + + "userid=" + username + + "&password=" + password + + "&send_to=" + sendTo + + "&v=1.1&format=json" + + "&msg_type=IMAGE" + + "&method=SENDMEDIAMESSAGE" + + "&caption=%2AGCC+Toilets+Monitoring%2A%0A%0AToday%27s+%28" + msgDate + + "%29+Zone+wise+Toilets+Evening+inspection+details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." + + "&media_url=" + fileURL + + "&isTemplate=true&footer=GCC+-+IT+Cell"; + + urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" + + "&apikey=" + apikey + + "&from=" + from + + "&to={{to}}&templateid=2784943" + + "&url=" + fileURL + + "&placeholders=Zone%20wise%20Toilets%20Evening%20inspection%20details"; + break; + + case "10": + System.out.println("TempID is 10 (Bus Shelter Monitoring -> 1508454 - gcc_bus_shelter_monitoring)"); + urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" + + "userid=" + username + + "&password=" + password + + "&send_to=" + sendTo + + "&v=1.1&format=json" + + "&msg_type=IMAGE" + + "&method=SENDMEDIAMESSAGE" + + "&caption=%2AGCC+Bus+Shelter+Monitoring%2A%0A%0AToday%27s+%28" + msgDate + + "%29+Zone+wise+Bus+Shelter+inspection+details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." + + "&media_url=" + fileURL + + "&isTemplate=true&footer=GCC+-+IT+Cell"; + + urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" + + "&apikey=" + apikey + + "&from=" + from + + "&to={{to}}&templateid=2784943" + + "&url=" + fileURL + + "&placeholders=Zone%20wise%20Bus%20Shelter%20inspection%20details"; + break; + + case "11": + System.out.println("TempID is 11 (Still Catch Pit -> 1566758 - silt_catch_pit_cleaning )"); + urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" + + "userid=" + username + + "&password=" + password + + "&send_to=" + sendTo + + "&v=1.1&format=json" + + "&msg_type=IMAGE" + + "&method=SENDMEDIAMESSAGE" + + "&caption=%2AGCC+Silt+catch+Pit+Cleaning%2A%0A%0AToday%27s+%28" + msgDate + + "%29+Zone+wise+Silt+Catch+Pit+cleaning+details+shared+above+for+your+reference%0A%0AFor+more+details%2C+please+click+the+link+below." + + "&media_url=" + fileURL + + "&isTemplate=true&footer=GCC+-+IT+Cell"; + + urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" + + "&apikey=" + apikey + + "&from=" + from + + "&to={{to}}&templateid=2784943" + + "&url=" + fileURL + + "&placeholders=Zone%20wise%20Silt%20Catch%20Pit%20cleaning%20details"; + break; + + case "12": + System.out.println("TempID is 12 (1590940 - tree_planting_gcc - IMAGE - STATIC)"); + urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" + + "userid=" + username + + "&password=" + password + + "&send_to=" + sendTo + + "&v=1.1&format=json" + + "&msg_type=IMAGE" + + "&method=SENDMEDIAMESSAGE" + + "&caption=%2AGCC+Tree+Planting%2A%0A%0AToday%27s+%28" + msgDate + + "%29+Zone+wise+tree+planting+details+shared+above+for+your+reference%0A%0AFor+more+details%2C+please+click+the+link+below." + + "&media_url=" + fileURL + + "&isTemplate=true&footer=GCC+-+IT+Cell"; + + urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" + + "&apikey=" + apikey + + "&from=" + from + + "&to={{to}}&templateid=2784943" + + "&url=" + fileURL + + "&placeholders=Zone%20wise%20tree%20planting%20details"; + break; + + case "13": + System.out.println("TempID is 13 (1590940 - Chennai Schools (userd of Com Temp ) - IMAGE - STATIC)"); + urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" + + "userid=" + username + + "&password=" + password + + "&send_to=" + sendTo + + "&v=1.1&format=json" + + "&msg_type=IMAGE" + + "&method=SENDMEDIAMESSAGE" + // + + // "&caption=%2AGCC+The+Chennai+School%2A%0A%0AToday%27s+%28"+msgDate+"%29+Zone+wise+Students+Aadhar+linked+details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." + + "&caption=%2AGCC+The+Chennai+School%2A%0A%0AToday%27s+%28" + msgDate + + "%29+Zone+wise+Students+Aadhar+linked+details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." + + "&media_url=" + fileURL + + "&isTemplate=true&footer=GCC+-+IT+Cell"; + + urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" + + "&apikey=" + apikey + + "&from=" + from + + "&to={{to}}&templateid=2784943" + + "&url=" + fileURL + + "&placeholders=Zone%20wise%20Students%20Aadhar%20linked%20details"; + break; + + case "14": + System.out.println("TempID is 14 (1943196 - pet_wp_report - IMAGE - STATIC)"); + urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" + + "userid=" + username + + "&password=" + password + + "&send_to=" + sendTo + + "&v=1.1&format=json" + + "&msg_type=IMAGE" + + "&method=SENDMEDIAMESSAGE" + // + + // "&caption=%2AGCC+The+Chennai+School%2A%0A%0AToday%27s+%28"+msgDate+"%29+Zone+wise+Students+Aadhar+linked+details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." + + "&caption=%2AGCC+PET+LICENSE+%26+VACCINATION%2A%0A%0AToday%27s+%28" + msgDate + + "%29+Zone+wise+Pet+license+%26+Vaccination+details+shared+above+for+your+kind+reference." + + "&media_url=" + fileURL + + "&isTemplate=true&footer=GCC+-+IT+Cell"; + + urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" + + "&apikey=" + apikey + + "&from=" + from + + "&to={{to}}&templateid=2784943" + + "&url=" + fileURL + + "&placeholders=Zone%20wise%20Pet%20license%20%26%20Vaccination%20details"; + break; + + case "15": + System.out.println( + "TempID is 15 (1590940 - GCC POS Penalty Monitoring Zone (userd of Com Temp ) - IMAGE - STATIC)"); + urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" + + "userid=" + username + + "&password=" + password + + "&send_to=" + sendTo + + "&v=1.1&format=json" + + "&msg_type=IMAGE" + + "&method=SENDMEDIAMESSAGE" + + "&caption=%2AGCC+POS+Penalty+Monitoring%2A%0A%0AToday%27s+%28" + msgDate + + "%29++POS+Penalty+Zone+wise+details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." + + "&media_url=" + fileURL + + "&isTemplate=true&footer=GCC+-+IT+Cell"; + + urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" + + "&apikey=" + apikey + + "&from=" + from + + "&to={{to}}&templateid=2784943" + + "&url=" + fileURL + + "&placeholders=POS%20Penalty%20Zone%20wise%20details"; + + break; + + case "16": + System.out.println( + "TempID is 16 (1590940 - GCC POS Penalty Monitoring Catagory (userd of Com Temp ) - IMAGE - STATIC)"); + urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" + + "userid=" + username + + "&password=" + password + + "&send_to=" + sendTo + + "&v=1.1&format=json" + + "&msg_type=IMAGE" + + "&method=SENDMEDIAMESSAGE" + + "&caption=%2AGCC+POS+Penalty+Monitoring%2A%0A%0AToday%27s+%28" + msgDate + + "%29++POS+Penalty+Catagory+wise+details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." + + "&media_url=" + fileURL + + "&isTemplate=true&footer=GCC+-+IT+Cell"; + + urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" + + "&apikey=" + apikey + + "&from=" + from + + "&to={{to}}&templateid=2784943" + + "&url=" + fileURL + + "&placeholders=POS%20Penalty%20Catagory%20wise%20details"; + break; + + case "17": + System.out.println( + "TempID is 17 (1590940 - GCC Enforcement Team Monitoring Temp (userd of Com Temp ) - IMAGE - STATIC)"); + urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" + + "userid=" + username + + "&password=" + password + + "&send_to=" + sendTo + + "&v=1.1&format=json" + + "&msg_type=IMAGE" + + "&method=SENDMEDIAMESSAGE" + + "&caption=%2AGCC+Enforcement+Team+Monitoring%2A%0A%0AToday%27s+%28" + msgDate + + "%29+Zone+wise+Enforcement+Team+activity+details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." + + "&media_url=" + fileURL + + "&isTemplate=true&footer=GCC+-+IT+Cell"; + + urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" + + "&apikey=" + apikey + + "&from=" + from + + "&to={{to}}&templateid=2784943" + + "&url=" + fileURL + + "&placeholders=Zone%20wise%20Enforcement%20Team%20activity%20details"; + + break; + + case "21": + System.out.println("TempID is 21 (1590940 - Namma Salai - IMAGE - STATIC)"); + urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" + + "userid=" + username + + "&password=" + password + + "&send_to=" + sendTo + + "&v=1.1&format=json" + + "&msg_type=IMAGE" + + "&method=SENDMEDIAMESSAGE" + + "&caption=%2AGCC+Enforcement+Team+Monitoring%2A%0A%0AToday%27s+%28" + msgDate + + "%29+Zone+wise+Enforcement+Team+activity+details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." + + "&media_url=" + fileURL + + "&isTemplate=true&footer=GCC+-+IT+Cell"; + + urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" + + "&apikey=" + apikey + + "&from=" + from + + "&to={{to}}&templateid=2784943" + + "&url=" + fileURL + + "&placeholders=Namma%20salai%20activity%20details"; + + break; + + case "22": + System.out.println("TempID is 22 (1590940 - Victoria Hall Booking - IMAGE - STATIC)"); + urlString = "https://media.smsgupshup.com/GatewayAPI/rest?" + + "userid=" + username + + "&password=" + password + + "&send_to=" + sendTo + + "&v=1.1&format=json" + + "&msg_type=IMAGE" + + "&method=SENDMEDIAMESSAGE" + + "&caption=%2AGCC+Enforcement+Team+Monitoring%2A%0A%0AToday%27s+%28" + msgDate + + "%29+Zone+wise+Enforcement+Team+activity+details+shared+above+for+your+reference.%0A%0AFor+more+details%2C+please+click+the+link+below." + + "&media_url=" + fileURL + + "&isTemplate=true&footer=GCC+-+IT+Cell"; + + urlString = "https://sendapiv1.pinbot.ai/pinwa/sendMessage?type=template" + + "&apikey=" + apikey + + "&from=" + from + + "&to={{to}}&templateid=2784943" + + "&url=" + fileURL + + "&placeholders=Victoria%20Hall%20Booking%20Details"; + + break; + + default: + System.out.println("TempID (" + tempid + ") is unknown"); + } + + if (!urlString.isBlank()) { + sql = "SELECT `id`, `name`, `mobile`, `userid`, `tempids` FROM `send_msg_to` WHERE `isactive` = 1 AND `isdelete` = 0 AND FIND_IN_SET(?, tempids);"; + List> mobileResult2 = jdbcTemplate.queryForList(sql, tempid); + for (Map mobileRow2 : mobileResult2) { + String mobile = String.valueOf(mobileRow2.get("mobile")); + String finalUrl = urlString.replace("{{to}}", mobile); + String response = sendWhatsAppMessage(finalUrl); + System.out.println("WhatsApp response: " + response); + } + } + + return "success"; + } + + private String sendWhatsAppMessage(String urlString) { + String response = ""; + try { + URL url = new URL(urlString); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("GET"); + + int responseCode = connection.getResponseCode(); + response = String.valueOf(responseCode); + System.out.println("Response Code for URL: " + urlString + " is " + responseCode); + + } catch (Exception e) { + e.printStackTrace(); + } + return response; + } + + public String disablemessage(String msgid) { + String sql = "update message_list set isdelete =1, isactive = 0 where id = ?"; int rowsAffected = jdbcTemplate.update(sql, msgid); if (rowsAffected > 0) { return "success"; - }else { + } else { return "failed"; } - } + } - public String enableMessage(String msgid) { - String sql = "update message_list set isdelete =0, isactive = 1 where id = ?"; + public String enableMessage(String msgid) { + String sql = "update message_list set isdelete =0, isactive = 1 where id = ?"; - int rowsAffected = jdbcTemplate.update(sql, msgid); + int rowsAffected = jdbcTemplate.update(sql, msgid); - if (rowsAffected > 0) { - return "success"; - }else { - return "failed"; - } - } + if (rowsAffected > 0) { + return "success"; + } else { + return "failed"; + } + } } diff --git a/gcc_officer_portal/src/main/resources/application.properties b/gcc_officer_portal/src/main/resources/application.properties index acd734ca..e4b93c87 100644 --- a/gcc_officer_portal/src/main/resources/application.properties +++ b/gcc_officer_portal/src/main/resources/application.properties @@ -1,5 +1,5 @@ -spring.profiles.active=local -# spring.profiles.active=production +# spring.profiles.active=local +spring.profiles.active=production #For Server production #assets.base-url=/gcc/assets/ #For local test