diff --git a/.DS_Store b/.DS_Store index 03a2b26..7b6c89d 100644 Binary files a/.DS_Store and b/.DS_Store differ diff --git a/mobileservice/.DS_Store b/mobileservice/.DS_Store index 70b7800..d941638 100644 Binary files a/mobileservice/.DS_Store and b/mobileservice/.DS_Store differ diff --git a/mobileservice/src/.DS_Store b/mobileservice/src/.DS_Store index 41362cc..43bd6ff 100644 Binary files a/mobileservice/src/.DS_Store and b/mobileservice/src/.DS_Store differ diff --git a/mobileservice/src/main/.DS_Store b/mobileservice/src/main/.DS_Store index 44b9c1e..a1913bb 100644 Binary files a/mobileservice/src/main/.DS_Store and b/mobileservice/src/main/.DS_Store differ diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/1_approved.jpg b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/1_approved.jpg deleted file mode 100644 index 1c44c29..0000000 Binary files a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/1_approved.jpg and /dev/null differ diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/1_rejected.jpg b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/1_rejected.jpg deleted file mode 100644 index dbe75ba..0000000 Binary files a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/1_rejected.jpg and /dev/null differ diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/configuration/DataSourceConfig.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/configuration/DataSourceConfig.java index d06d9b3..f5430c8 100644 --- a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/configuration/DataSourceConfig.java +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/configuration/DataSourceConfig.java @@ -104,7 +104,17 @@ public class DataSourceConfig { return dataSource; } - + //////////////////////////////(For Cattle Catch Master) //////////////////////// + @Bean(name = "mysqlHoardingsDataSource") + public DataSource mysqlHoardingsDataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); + dataSource.setUrl("jdbc:mysql://"+host+"/gcc_penalty_hoardings"); + dataSource.setUsername("root"); + dataSource.setPassword(dbpassword); + return dataSource; + } + //////////////////////////////(For PGR Master) //////////////////////// @Bean(name = "mysqlPGRMasterDataSource") public DataSource mysqlPGRMasterDataSource() { @@ -182,6 +192,16 @@ public class DataSourceConfig { return dataSource; } + //////////////////////////////(For Schools) //////////////////////// + @Bean(name = "mysqlToiletsDataSource") + public DataSource mysqlToiletsDataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); + dataSource.setUrl("jdbc:mysql://"+host+"/gcc_toilets"); + dataSource.setUsername("root"); + dataSource.setPassword(dbpassword); + return dataSource; + } ////////////////////////////// ORACLE //////////////////////// @Bean(name = "oracleERPDataSource") diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccactivity/service/Activity.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccactivity/service/Activity.java index 0df46a2..46ff50d 100644 --- a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccactivity/service/Activity.java +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccactivity/service/Activity.java @@ -799,7 +799,7 @@ public String assetFileUpload(String catId, MultipartFile file) { // Step 1: Generate all dates within the specified month and year String sqlQueryForTasks = "SELECT " - + " `asset_list`.`id`," + + " `asset_list`.`id`, " + " `asset_list`.`category_id`, " + " `asset_list`.`image`, " + " `asset_list`.`latitude`, " @@ -817,14 +817,14 @@ public String assetFileUpload(String catId, MultipartFile file) { + "FROM " + " `activity_feedback` " + "JOIN " - + " `asset_list` ON `asset_list`.`id` = `activity_feedback`.`asset_id` " + + " `asset_list` " + + " ON `asset_list`.`id` = `activity_feedback`.`asset_id` " + "WHERE " - + " DATE_FORMAT(`activity_feedback`.`feedback_date`, '%d-%m-%Y') BETWEEN ? AND ? " - + "AND " - + " `asset_list`.`category_id` = ? " - + "AND " - + " `asset_list`.`streetid` = ? " - + "AND (`asset_list`.`isactive`=1 AND `asset_list`.`isdelete`=0) " + + " DATE(`activity_feedback`.`feedback_date`) BETWEEN STR_TO_DATE(?, '%d-%m-%Y') AND STR_TO_DATE(?, '%d-%m-%Y') " + + " AND `asset_list`.`category_id` = ? " + + " AND `asset_list`.`streetid` = ? " + + " AND `asset_list`.`isactive` = 1 " + + " AND `asset_list`.`isdelete` = 0 " + "GROUP BY " + " `asset_list`.`id`"; diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccparks/controller/ParksController.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccparks/controller/ParksController.java index 9112fe1..5009eaa 100644 --- a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccparks/controller/ParksController.java +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccparks/controller/ParksController.java @@ -534,10 +534,10 @@ public class ParksController { // ------------------------------------------Enumeration Report // API----------------------------------------------------- - @GetMapping("/zoneCount") + @GetMapping("/zoneCount") // UserId added public ResponseEntity>> getZoneCount(@RequestParam("fromdate") String fromdate, @RequestParam("todate") String todate, @RequestParam("enumeration_type") String enumeration_type, - @RequestParam("userId") String userId) throws Exception { + @RequestParam(value = "userId", required = false) String userId) throws Exception { List> zoneCountData = parksService.getZoneCount(fromdate, todate, enumeration_type, userId); if (zoneCountData == null || zoneCountData.isEmpty()) { @@ -547,11 +547,11 @@ public class ParksController { } - @GetMapping("/wardCount") + @GetMapping("/wardCount") // Zone added public ResponseEntity>> getwardCount(@RequestParam("zone") String zone, - @RequestParam("userId") String userId, @RequestParam("fromdate") String fromdate, + @RequestParam(value = "userId", required = false) String userId, @RequestParam("fromdate") String fromdate, @RequestParam("todate") String todate, @RequestParam("enumeration_type") String enumeration_type) - throws Exception { + throws Exception { List> wardCountData = parksService.getwardCount(zone, fromdate, todate, enumeration_type, userId); if (wardCountData == null || wardCountData.isEmpty()) { @@ -561,13 +561,14 @@ public class ParksController { } - @GetMapping("/activityCount") + @GetMapping("/activityCount") // userId and Zone added public ResponseEntity>> getActivityCount(@RequestParam("ward") String ward, @RequestParam("fromdate") String fromdate, @RequestParam("todate") String todate, - @RequestParam("enumeration_type") String enumeration_type) throws Exception { + @RequestParam("enumeration_type") String enumeration_type, @RequestParam(value="userId", required = false) String userId, + @RequestParam("zone") String zone) throws Exception { List> activityByWard = parksService.getActivityCount(ward, fromdate, todate, - enumeration_type); + enumeration_type, zone, userId); if (activityByWard == null || activityByWard.isEmpty()) { throw new NoDataException("No Activity is performed "); } @@ -575,14 +576,14 @@ public class ParksController { } - @GetMapping("/activityDetails") + @GetMapping("/activityDetails") // userId and Zone added public ResponseEntity>> getActivityDetails(@RequestParam("ward") String ward, @RequestParam("fromdate") String fromdate, @RequestParam("todate") String todate, - @RequestParam("enumeration_type") String enumeration_type, - @RequestParam("enumerationId") String enumerationId) throws Exception { + @RequestParam("enumeration_type") String enumeration_type,@RequestParam("enumerationId") String enumerationId, + @RequestParam(value="userId", required= false) String userId, @RequestParam("zone") String zone) throws Exception { List> activityDetailsByWard = parksService.getActivityDetails(ward, fromdate, todate, - enumeration_type, enumerationId); + enumeration_type, enumerationId, zone, userId); if (activityDetailsByWard == null || activityDetailsByWard.isEmpty()) { throw new NoDataException("no data "); } @@ -590,10 +591,11 @@ public class ParksController { } - @GetMapping("/getInspectionDetails") + @GetMapping("/getInspectionDetails") // zone, ward and userId added check it in last public ResponseEntity>>> getInspectionDetails( @RequestParam("activityId") String activityId, @RequestParam("fromdate") String fromdate, - @RequestParam("todate") String todate, @RequestParam("enumerationId") String enumerationId) + @RequestParam("todate") String todate, @RequestParam("enumerationId") String enumerationId, + @RequestParam(value="userId", required = false) String userId ) throws Exception { List>> activityDetailsByWard = parksService.getInspectionDetails(activityId, fromdate, @@ -602,7 +604,7 @@ public class ParksController { throw new NoDataException("no data "); } return ResponseEntity.ok(activityDetailsByWard); - + } // tofxcvbn diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccparks/service/ParksService.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccparks/service/ParksService.java index f0bec74..98616b7 100644 --- a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccparks/service/ParksService.java +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccparks/service/ParksService.java @@ -1408,64 +1408,117 @@ public class ParksService { */ public List> getZoneCount(String fromdate, String todate, String enumeration_type, String userId ) throws Exception { - String sql = "SELECT zone,count(enumeration_Id) as count FROM enumeration_master" - + " where enumeration_type=(?) and UserId = ? and DATE(cdate) BETWEEN STR_TO_DATE('" + fromdate + "', '%d-%m-%Y') " - + "AND STR_TO_DATE('" + todate + "', '%d-%m-%Y') group by zone "; - + StringBuilder sql = new StringBuilder("SELECT zone,count(enumeration_Id) as count FROM enumeration_master" + + " where enumeration_type=(?) and DATE(cdate) BETWEEN STR_TO_DATE(? , '%d-%m-%Y') " + + "AND STR_TO_DATE(? , '%d-%m-%Y') "); - return jdbcParkseTemplate.queryForList(sql, new Object[] { enumeration_type, userId}); - - } - /* 23-11-2024 Patch - public List> getwardCount(String zone, String fromdate, String todate, - String enumeration_type) { - String sql = " SELECT ward,count(enumeration_Id) as count FROM enumeration_master " - + "where zone=(?) and date(cdate) between STR_TO_DATE('" + fromdate + "', '%d-%m-%Y') " - + "and STR_TO_DATE('" + todate + "', '%d-%m-%Y') And enumeration_type =(?) group by ward "; - return jdbcParkseTemplate.queryForList(sql, new Object[] { zone, enumeration_type }); + List params = new ArrayList<>(); + params.add(enumeration_type); + params.add(fromdate); + params.add(todate); + +// if (userId != null) { +// sql.append(" AND UserId = ?"); +// params.add(userId); +// } + + sql.append(" GROUP BY zone"); + + return jdbcParkseTemplate.queryForList(sql.toString(), params.toArray()); } - */ public List> getwardCount(String zone, String fromdate, String todate, String enumeration_type, String userId) { - String sql = " SELECT ward,count(enumeration_Id) as count FROM enumeration_master " - + "where zone=(?) and UserId = ? and date(cdate) between STR_TO_DATE('" + fromdate + "', '%d-%m-%Y') " - + "and STR_TO_DATE('" + todate + "', '%d-%m-%Y') And enumeration_type =(?) group by ward "; - return jdbcParkseTemplate.queryForList(sql, new Object[] { zone, enumeration_type, userId }); + + StringBuilder sql = new StringBuilder(" SELECT ward,count(enumeration_Id) as count FROM enumeration_master " + + "where zone=(?) and date(cdate) between STR_TO_DATE(? , '%d-%m-%Y') " + + "and STR_TO_DATE(? , '%d-%m-%Y') And enumeration_type =(?)"); + + List params = new ArrayList<>(); + params.add(zone); + params.add(fromdate); + params.add(todate); + params.add(enumeration_type); + +// if (userId != null) { +// sql.append(" AND UserId = ?"); +// params.add(userId); +// } + + sql.append(" group by ward"); + + return jdbcParkseTemplate.queryForList(sql.toString(), params.toArray()); } - + + public List> getActivityCount(String ward, String fromdate, String todate, - String enumeration_type) { - /*String sql = "select act.feedback_enumeration_Id, act.ward,coalesce(em.park_name,em.location) AS location_Park," - + "count(act.feedback_enumeration_Id) as count from activity act left join enumeration_master em on " - + "em.enumeration_Id = act.feedback_enumeration_Id where act.ward=? and act.feedback_enumeration_Type= ? " - + "and date(act.cdate) between STR_TO_DATE('" + fromdate + "', '%d-%m-%Y') and " - + "STR_TO_DATE('" + todate + "', '%d-%m-%Y') group by act.feedback_enumeration_Id, act.ward, location_Park";*/ + String enumeration_type, String zone, String userId) { + + + StringBuilder sql = new StringBuilder("SELECT " + + " em.enumeration_Id AS feedback_enumeration_Id, " + + " em.ward, " + + " COALESCE(em.park_name, em.location) AS location_Park, " + + " COUNT(act.feedback_enumeration_Id) AS count " + + "FROM " + + " enumeration_master em " + + "LEFT JOIN " + + " activity act ON act.feedback_enumeration_Id = em.enumeration_Id " + + " AND em.enumeration_Type = ?" + + " AND DATE(act.cdate) BETWEEN STR_TO_DATE( '"+fromdate+"' , '%d-%m-%Y') " + + " AND STR_TO_DATE('"+todate+"', '%d-%m-%Y') " + + "WHERE " + + " em.ward = ? " + + " AND em.zone = ? " + + " AND DATE(em.cdate) BETWEEN STR_TO_DATE('"+fromdate+"', '%d-%m-%Y') " + + " AND STR_TO_DATE('"+todate+"' , '%d-%m-%Y') " ); - String sql = "select em.enumeration_Id as feedback_enumeration_Id, em.ward, coalesce(em.park_name,em.location) AS location_Park, count(act.feedback_enumeration_Id) as count " - + "from enumeration_master em " - + "left join activity act on act.feedback_enumeration_Id = em.enumeration_Id " - + "where act.ward = ? and act.feedback_enumeration_Type = ? " - + "and date(act.cdate) between STR_TO_DATE('" + fromdate + "', '%d-%m-%Y') and STR_TO_DATE('" + todate + "', '%d-%m-%Y') " - + "group by em.enumeration_Id, em.ward"; + List params = new ArrayList<>(); + params.add(enumeration_type); + params.add(ward); + params.add(zone); - return jdbcParkseTemplate.queryForList(sql, new Object[] { ward, enumeration_type}); + sql.append(" GROUP BY em.enumeration_Id, em.ward, em.park_name, em.location"); + +// if (userId != null) { +// sql.append(" and act.user_Id = ?"); +// params.add(userId); +// } + + + return jdbcParkseTemplate.queryForList(sql.toString(), params.toArray()); } public List> getActivityDetails(String ward, String fromdate, String todate, - String enumeration_type, String enumerationId) { - String sql = "SELECT act.feedback_enumeration_Id,act.activity_id, DATE_FORMAT(act.cdate, '%d-%m-%Y %l:%i %p') AS date, " - + "act.feedback_latitude, act.feedback_longitude, et.enumerationName " + "FROM activity act " + String enumeration_type, String enumerationId, String zone, String userId ) { + + StringBuilder sql = new StringBuilder( "SELECT act.feedback_enumeration_Id,act.activity_id, DATE_FORMAT(act.cdate, '%d-%m-%Y %l:%i %p') AS date, " + + "act.feedback_latitude, act.feedback_longitude, et.enumerationName FROM activity act " + "LEFT JOIN enumerationtype et ON et.enumeration_type_id = act.feedback_enumeration_Type " - + "WHERE act.ward = ? " + "AND act.feedback_enumeration_Type = ? " - + "AND DATE(act.cdate) BETWEEN STR_TO_DATE('" + fromdate + "', '%d-%m-%Y') AND STR_TO_DATE('" + todate + "', '%d-%m-%Y') " - + "and act.feedback_enumeration_Id = ?" - + "GROUP BY act.feedback_enumeration_Id,act.activity_id, act.feedback_latitude, act.feedback_longitude, et.enumerationName"; + + "WHERE act.ward = ? and act.feedback_zone = ? AND act.feedback_enumeration_Type = ? " + + "AND DATE(act.cdate) BETWEEN STR_TO_DATE(? , '%d-%m-%Y') AND STR_TO_DATE(? , '%d-%m-%Y') " + + "and act.feedback_enumeration_Id = ?"); + + List params = new ArrayList<>(); + params.add(ward); + params.add(zone); + params.add(enumeration_type); + params.add(fromdate); + params.add(todate); + params.add(enumerationId); + + +// if (userId != null) { +// sql.append(" and act.user_Id = ?"); +// params.add(userId); +// } + + sql.append(" GROUP BY act.feedback_enumeration_Id,act.activity_id, act.feedback_latitude, act.feedback_longitude, et.enumerationName"); - return jdbcParkseTemplate.queryForList(sql, new Object[] { ward, enumeration_type, enumerationId }); + return jdbcParkseTemplate.queryForList(sql.toString(),params.toArray()); } @@ -1503,7 +1556,7 @@ public class ParksService { String sql = "select eqm.qa_name, fb.feedback_Name from feedback fb " + "left join enu_question_master eqm on eqm.qa_id = fb.feedback_qa_id " + "left join activity act on act.activity_id = fb.activity_id " - + "where fb.activity_id =? and date(act.cdate) between STR_TO_DATE(' "+ fromdate + " ','%Y-%m-%d') and STR_TO_DATE('"+todate+"','%Y-%m-%d')"; + + "where fb.activity_id =? and date(act.cdate) between STR_TO_DATE(' "+ fromdate + " ','%d-%m-%Y') and STR_TO_DATE('"+todate+"','%d-%m-%Y')"; return jdbcParkseTemplate.queryForList(sql, new Object[] { activityId }); } @@ -1513,7 +1566,7 @@ public class ParksService { String sql = "select *,coalesce(em.park_name,em.location) as parkName, " + "CONCAT('" + fileBaseUrl + "/gccofficialapp/files', eimg.photos_enu) AS imageUrl, em.latitude, em.longitude from enumertion_images eimg " + "left join enumeration_master em on em.enumeration_Id = eimg.enumerationImg_Id_master " - + "where eimg.enumerationImg_Id_master = ? and date(eimg.cdate) between STR_TO_DATE(' "+ fromdate + " ','%Y-%m-%d') and STR_TO_DATE('"+todate+"','%Y-%m-%d')"; + + "where eimg.enumerationImg_Id_master = ? and date(eimg.cdate) between STR_TO_DATE(' "+ fromdate + " ','%d-%m-%Y') and STR_TO_DATE('"+todate+"','%d-%m-%Y')"; return jdbcParkseTemplate.queryForList(sql, new Object[] { enumerationId }); } diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccschools/controller/SchoolUserController.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccschools/controller/SchoolUserController.java index 224cbfb..1dab6d3 100644 --- a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccschools/controller/SchoolUserController.java +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccschools/controller/SchoolUserController.java @@ -38,6 +38,18 @@ public class SchoolUserController { @Autowired private SchoolUserActivity schoolUserActivity; + @GetMapping("/getSchoolList") + public ResponseEntity>> getSchoolList(@RequestParam String ward, @RequestParam String category_type) { + List> schoolList = schoolUserActivity.getSchoolList(ward,category_type); + + if (schoolList.isEmpty()) { + // Return a "no data" message when the list is empty + return ResponseEntity.status(404).body(Collections.singletonList(Collections.singletonMap("message", "No data available"))); + } + + return ResponseEntity.ok(schoolList); + } + @PostMapping("/saveschool") public ResponseEntity saveSchool( @RequestParam String latitude, @@ -175,6 +187,9 @@ public class SchoolUserController { @RequestParam String typeoffacilitiesAns, @RequestParam(required = false) MultipartFile feedPhoto, + @RequestParam(required = false) MultipartFile storageofdrinkingPhoto, + @RequestParam(required = false) MultipartFile roPhoto, + @RequestParam(required = false) int school_details_id, @RequestParam String zone, @RequestParam String division, @@ -191,7 +206,8 @@ public class SchoolUserController { ROFacilitiesAvailableQa, ROFacilitiesAvailableAns, ROGoodConditionQa, ROGoodConditionAns,DrinkingwaterfacilitiesQa,DrinkingwaterfacilitiesAns, typeoffacilitiesQa,typeoffacilitiesAns, - feedPhoto, school_details_id, zone, division,latitude,longitude,user_id); + feedPhoto, storageofdrinkingPhoto, roPhoto, + school_details_id, zone, division,latitude,longitude,user_id); return new ResponseEntity<>("Feedback saved successfully.", HttpStatus.OK); } catch (Exception e) { @@ -360,6 +376,7 @@ public class SchoolUserController { return new ResponseEntity<>("Failed to save feedback: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } } + @PostMapping("/ITAssets") public ResponseEntity ITAssets( @RequestParam int categoryId, @@ -375,6 +392,10 @@ public class SchoolUserController { @RequestParam String UPSAvailableAns, @RequestParam String UPSNotAvailableQa, @RequestParam String UPSNotAvailableAns, + @RequestParam(required = false) String CCTVAvailableQa, + @RequestParam(required = false) String CCTVAvailableAns, + @RequestParam(required = false) String CCTVNotAvailableQa, + @RequestParam(required = false) String CCTVNotAvailableAns, @RequestParam String NetworkAvailableQa, @RequestParam String NetworkAvailableAns, @RequestParam String projectorgoodconditionQa, @@ -396,6 +417,7 @@ public class SchoolUserController { SystemAvailableQa, SystemAvailableAns, SystemNotAvailableQa, SystemNotAvailableAns, PrinterAvailableQa, PrinterAvailableAns, PrinterNotAvailableQa, PrinterNotAvailableAns, UPSAvailableQa, UPSAvailableAns, UPSNotAvailableQa, UPSNotAvailableAns, + CCTVAvailableQa, CCTVAvailableAns, CCTVNotAvailableQa, CCTVNotAvailableAns, NetworkAvailableQa, NetworkAvailableAns, projectorgoodconditionQa, projectorgoodconditionAns, smartboardgoodconditionQa, smartboardgoodconditionAns, @@ -893,26 +915,26 @@ public class SchoolUserController { @PostMapping("/saveClusterKitchen") public ResponseEntity ClusterKitchen( - @RequestParam int categoryId, - @RequestParam String ClusterKitchencleanandneatQa, - @RequestParam String ClusterKitchencleanandneatAns, - @RequestParam String SampleoffoodmaintainedQa, - @RequestParam String SampleoffoodmaintainedAns, - @RequestParam String cookingstaffwearingQa, - @RequestParam String cookingstaffwearingAns, - @RequestParam String fooditemsmatchwiththestockQa , - @RequestParam String fooditemsmatchwiththestockAns, - @RequestParam String FooditemsusedofgoodqualityQa , - @RequestParam String FooditemsusedofgoodqualityAns, - @RequestParam(required = false) MultipartFile feedPhoto, - @RequestParam(required = false) int school_details_id, - @RequestParam String zone, - @RequestParam String division, - @RequestParam Double latitude, - @RequestParam double longitude, - @RequestParam String user_id, - @RequestParam (required = false) String question_id -) { + @RequestParam int categoryId, + @RequestParam String ClusterKitchencleanandneatQa, + @RequestParam String ClusterKitchencleanandneatAns, + @RequestParam String SampleoffoodmaintainedQa, + @RequestParam String SampleoffoodmaintainedAns, + @RequestParam String cookingstaffwearingQa, + @RequestParam String cookingstaffwearingAns, + @RequestParam String fooditemsmatchwiththestockQa , + @RequestParam String fooditemsmatchwiththestockAns, + @RequestParam String FooditemsusedofgoodqualityQa , + @RequestParam String FooditemsusedofgoodqualityAns, + @RequestParam(required = false) MultipartFile feedPhoto, + @RequestParam(required = false) int school_details_id, + @RequestParam String zone, + @RequestParam String division, + @RequestParam double latitude, + @RequestParam double longitude, + @RequestParam String user_id, + @RequestParam (required = false) String question_id + ) { try { // Call the service method to save feedback @@ -931,4 +953,85 @@ public class SchoolUserController { return new ResponseEntity<>("Failed to save feedback: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } } + + @PostMapping("/savePlayFields") + public ResponseEntity PlayFields( + @RequestParam int categoryId, + @RequestParam String playfieldavailableQa, + @RequestParam String playfieldavailableAns, + @RequestParam String civilworkQa, + @RequestParam String civilworkAns, + @RequestParam String electricalworkQa, + @RequestParam String electricalworkAns, + @RequestParam String sportsmaterialkQa , + @RequestParam String sportsmaterialAns, + @RequestParam(required = false) MultipartFile playfieldPhoto, + @RequestParam(required = false) MultipartFile civilworkPhoto, + @RequestParam(required = false) int school_details_id, + @RequestParam String zone, + @RequestParam String division, + @RequestParam double latitude, + @RequestParam double longitude, + @RequestParam String user_id, + @RequestParam (required = false) String question_id + ) { + + try { + // Call the service method to save feedback + + + schoolUserActivity.savePlayFields( + categoryId, + playfieldavailableQa, playfieldavailableAns, + civilworkQa, civilworkAns, + electricalworkQa, electricalworkAns, + sportsmaterialkQa, sportsmaterialAns, + playfieldPhoto, civilworkPhoto, + school_details_id, zone, division,latitude,longitude,user_id,question_id + ); + + return new ResponseEntity<>("Feedback saved successfully.", HttpStatus.OK); + } catch (Exception e) { + return new ResponseEntity<>("Failed to save feedback: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); + } + } + + //Complaints + + //saveComplaintReplay(String complaintId, String user_id, String replay, MultipartFile cPhoto); + //getComplaints(userId); + //getComplaintsReplay(comid); + + @GetMapping("/getComplaints") + public ResponseEntity>> Complaints(@RequestParam String user_id) { + List> ComplaintsList = schoolUserActivity.getComplaints(user_id); + return ResponseEntity.ok(ComplaintsList); + } + + @PostMapping("/saveComplaintReplay") + public ResponseEntity complaintReplay( + @RequestParam String complaintId, + @RequestParam String replay, + @RequestParam(required = true) MultipartFile file, + @RequestParam String user_id +) { + + try { + // Call the service method to save feedback + schoolUserActivity.saveComplaintReplay( + complaintId,user_id,replay,file + ); + + return new ResponseEntity<>("Complaint replay saved successfully.", HttpStatus.OK); + } catch (Exception e) { + return new ResponseEntity<>("Failed to save Complaint replay: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); + } + } + + @GetMapping("/getComplaintsReplay") + public ResponseEntity>> ComplaintsReplay(@RequestParam String comid) { + List> ComplaintReplayList = schoolUserActivity.getComplaintsReplay(comid); + return ResponseEntity.ok(ComplaintReplayList); + } + } diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccschools/service/SchoolUserActivity.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccschools/service/SchoolUserActivity.java index 69f5110..f3b53c4 100644 --- a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccschools/service/SchoolUserActivity.java +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/gccschools/service/SchoolUserActivity.java @@ -69,6 +69,14 @@ public class SchoolUserActivity { 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(); + } + private byte[] compressImage(BufferedImage image, float quality) throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(byteArrayOutputStream); @@ -111,12 +119,13 @@ public class SchoolUserActivity { // Datetime string String datetimetxt = DateTimeUtil.getCurrentDateTime(); // File name - String fileName = name+ "_" +id + "_" + datetimetxt + "_" + file.getOriginalFilename(); + 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+"/"+fileName; + String filepath_txt = "/"+serviceFolderName + year + "/" + month + "/" + fileName; // Create a new Path object Path path = Paths.get(filePath); @@ -140,6 +149,11 @@ public class SchoolUserActivity { } } + public List> getSchoolList(String ward, String category_type) { + String sql = "SELECT * FROM school_list WHERE `division` = ? AND `category_type`= ? AND `gcc_app_updated`=0"; + return jdbcSchoolsTemplate.queryForList(sql,ward,category_type); + } + public void saveSchool(String latitude, String longitude, MultipartFile photo, Integer schoolType, String schoolName, String earmark, String zone, String division, String userId) { // Save or retrieve the school type ID based on schoolType //Integer schoolTypeId = saveSchoolType(schoolType); @@ -147,11 +161,24 @@ public class SchoolUserActivity { throw new IllegalArgumentException("Invalid school type ID: " + schoolType); } + // First, check if the school already exists based on the school name + String checkIfExistsSql = "SELECT id FROM school_details WHERE school_name = ?"; + + // Check if the school exists + List> existingSchool = jdbcSchoolsTemplate.queryForList(checkIfExistsSql, schoolName); + + // If the school exists, return the existing school ID + if (!existingSchool.isEmpty()) { + throw new IllegalArgumentException("School Name Alerdy Exits : " + existingSchool.get(0).get("id")); + } + // Save school details and retrieve the generated school_details_id int schoolDetailsId = saveSchoolDetails(latitude, longitude, schoolType, schoolName, earmark, zone, division, userId); + updateSchoolInactive(schoolName,schoolDetailsId); + String photoUrl = null; - + // Handle file upload if a photo is provided if (photo != null && !photo.isEmpty()) { // Make sure to pass the correct type for the first argument @@ -166,7 +193,16 @@ public class SchoolUserActivity { } } + private void updateSchoolInactive(String id, int schoolDetailsId) { + String sql = "UPDATE `school_list` SET `gcc_app_updated`=? WHERE `school_name`=?"; + jdbcSchoolsTemplate.update(sql, schoolDetailsId, id); + } + + + private int saveSchoolDetails(String latitude, String longitude, Integer schoolTypeId, String schoolName, String earmark, String zone, String division, String userId) { + + // SQL statement to insert school details String sql = "INSERT INTO school_details (latitude, longitude, school_type, school_name, earmark, zone, division, user_id) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ? )"; @@ -279,7 +315,7 @@ public class SchoolUserActivity { return newId; } - /////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////////// public Map getCategoryWithQuestions(int categoryId) { // Query to get category details String categorySql = "SELECT id, category FROM category WHERE id = ?"; @@ -363,7 +399,10 @@ public class SchoolUserActivity { String typeoffacilitiesQa, String typeoffacilitiesAns, - MultipartFile feedPhoto, // feedPhoto and schoolDetailsId were missing in the method signature + MultipartFile feedPhoto, // feedPhoto + MultipartFile storageofdrinkingPhoto, // storageofdrinkingPhoto + MultipartFile roPhoto, // roPhoto + int school_details_id, String zone, String division , @@ -372,6 +411,9 @@ public class SchoolUserActivity { String user_id) { String feedPhotoPath = null; + String storageofdrinkingPhotoPath = null; + String roPhotoPath = null; + String feedref = generateRandomString(); //generate feedback reference text // Handle file upload if a file is provided @@ -379,7 +421,23 @@ public class SchoolUserActivity { String id = String.valueOf(categoryId); String sdid = String.valueOf(school_details_id); feedPhotoPath = fileUpload(id, sdid, feedPhoto); // Adjusted to use schoolDetailsId - //feedPhotoPath = assetFileUpload(categoryId, feedPhoto, school_details_id); + + } + + // Handle file upload if a file is provided + if (storageofdrinkingPhoto != null && !storageofdrinkingPhoto.isEmpty()) { + String id = String.valueOf(categoryId); + String sdid = String.valueOf(school_details_id); + storageofdrinkingPhotoPath = fileUpload(id, sdid, storageofdrinkingPhoto); // Adjusted to use schoolDetailsId + + } + + // Handle file upload if a file is provided + if (roPhoto != null && !roPhoto.isEmpty()) { + String id = String.valueOf(categoryId); + String sdid = String.valueOf(school_details_id); + roPhotoPath = fileUpload(id, sdid, roPhoto); // Adjusted to use schoolDetailsId + } // Save feedback for each question and answer pair @@ -397,6 +455,18 @@ public class SchoolUserActivity { String qid = "33"; saveCategoryPhoto(categoryId, feedPhotoPath, qid, feedref); } + + // If a photo was uploaded, save it in the category_photos table + if (storageofdrinkingPhotoPath != null) { + String qid = "5"; + saveCategoryPhoto(categoryId, storageofdrinkingPhotoPath, qid, feedref); + } + + // If a photo was uploaded, save it in the category_photos table + if (roPhotoPath != null) { + String qid = "7"; + saveCategoryPhoto(categoryId, roPhotoPath, qid, feedref); + } } ///////////////////////////////////////////////// @@ -469,7 +539,7 @@ public class SchoolUserActivity { if (toiletfeedPhoto != null && !toiletfeedPhoto.isEmpty()) { String id = String.valueOf(categoryId); String sdid = String.valueOf(school_details_id); - toiletPhotoPath = fileUpload(id, sdid, RoomsfeedPhoto); // Adjusted to use schoolDetailsId + toiletPhotoPath = fileUpload(id, sdid, toiletfeedPhoto); // Adjusted to use schoolDetailsId //toiletPhotoPath = assetFileUpload(categoryId, toiletfeedPhoto, school_details_id); } @@ -483,7 +553,7 @@ public class SchoolUserActivity { if (PlaygroundfeedPhoto != null && !PlaygroundfeedPhoto.isEmpty()) { String id = String.valueOf(categoryId); String sdid = String.valueOf(school_details_id); - playgroundPhotoPath = fileUpload(id, sdid, RoomsfeedPhoto); // Adjusted to use schoolDetailsId + playgroundPhotoPath = fileUpload(id, sdid, PlaygroundfeedPhoto); // Adjusted to use schoolDetailsId //playgroundPhotoPath = assetFileUpload(categoryId, PlaygroundfeedPhoto, school_details_id); } @@ -631,6 +701,10 @@ public class SchoolUserActivity { String UPSAvailableAns, String UPSNotAvailableQa, String UPSNotAvailableAns, + String CCTVAvailableQa, + String CCTVAvailableAns, + String CCTVNotAvailableQa, + String CCTVNotAvailableAns, String NetworkAvailableQa, String NetworkAvailableAns, String projectorgoodconditionQa, @@ -685,8 +759,8 @@ public class SchoolUserActivity { int school_details_id, String zone, String division, - Double latitude , - Double longitude, + double latitude , + double longitude, String user_id) { // Add latitude parameter String feedref = generateRandomString(); //generate feedback reference text @@ -699,15 +773,54 @@ public class SchoolUserActivity { private void saveFeedbackDetails( int categoryId, String qid, String feedback, int school_details_id, String zone, String division, - double latitude,Double longitude,String user_id, + double latitude,double longitude,String user_id, String feedref) { String sql = "INSERT INTO feedback (cat_question_id, feedback, school_details_id, " + "zone, division, latitude, longitude, user_id, qid, feedref) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; // Execute SQL query to save feedback for the provided question jdbcSchoolsTemplate.update(sql, categoryId, feedback, school_details_id, zone, division, latitude, longitude, user_id, qid, feedref); - } + isComplaintRequired(""+categoryId, qid, feedref, ""+school_details_id, user_id, feedback); + + } + + private Boolean isComplaintRequired(String categoryId, String qid, String feedRef, String school_details_id, String user_id,String feedback) { + String sqlQuery="SELECT `category_questions`,`positive_ans`,`input_type` FROM `category_question` WHERE `id`= ? AND `risecompliance`=1 AND `is_active`=1"; + List> result = jdbcSchoolsTemplate.queryForList(sqlQuery, qid); + + if (result.isEmpty()) { + return false; + } + + // Build response map + String complaint_txt =""; + Map firstRow = result.get(0); + + complaint_txt = firstRow.get("category_questions").toString(); + String positive_ans = firstRow.get("positive_ans").toString(); + String input_type = firstRow.get("input_type").toString(); + + complaint_txt = complaint_txt + " : " + feedback; + + if(input_type.equals("radio")) { + + if(feedback != null && !feedback.trim().isEmpty() && !positive_ans.equals(feedback)) { + System.out.println("Radio:" + feedback + "Qid : " + qid); + createComplaint(categoryId, qid, feedRef, school_details_id, user_id, complaint_txt, feedback); + } + } + + if(input_type.equals("input_count")) { + + if(feedback != null && !feedback.trim().isEmpty() && !positive_ans.equals(feedback)) { + System.out.println("input_count:" + feedback + "Qid : " + qid); + createComplaint(categoryId, qid, feedRef, school_details_id, user_id, complaint_txt, feedback); + } + } + return true; + } + private void saveCategoryPhoto(int categoryId, String photoPath, String qid, String feedRef) { String sql = "INSERT INTO category_photos " + "(photo_url, is_active, is_deleted, category_id, qid, feedref) VALUES (?, ?, ?, ?, ?, ?)"; @@ -715,7 +828,44 @@ public class SchoolUserActivity { // Execute SQL query to save the photo path related to the category jdbcSchoolsTemplate.update(sql, photoPath, 1, 0, categoryId, qid, feedRef); } - //////////////////////////// + + + /// Complaints + + private void createComplaint(String categoryId, String qid, String feedRef, String school_details_id, String user_id, String complaint_txt, String feedback) { + System.out.println("Complaint : " + complaint_txt); + String sql = "INSERT INTO `complaints`(`cid`, `qid`, `feedref`, `school_details_id`, `user_id`, `complaint_txt`, `feedback`) " + + "VALUES (?,?,?,?,?,?,?)"; + + // Execute SQL query to save the photo path related to the category + jdbcSchoolsTemplate.update(sql, categoryId, qid, feedRef, school_details_id, user_id, complaint_txt,feedback); + } + + public void saveComplaintReplay(String complaintId, String user_id, String replay, MultipartFile cPhoto) { + String filePhotoPath=""; + // Handle file upload if a photo is provided + if (cPhoto != null && !cPhoto.isEmpty()) { + // Make sure to pass the correct type for the first argument + String id = String.valueOf(complaintId); + String sdid = String.valueOf(user_id); + filePhotoPath = fileUpload("reply_"+id, sdid, cPhoto); // Adjusted to use schoolDetailsId + } + + String sql = "INSERT INTO `complaints_reply`(`comid`, `replay`, `file`, `cby`) " + + "VALUES (?,?,?,?)"; + + // Execute SQL query to save the photo path related to the category + jdbcSchoolsTemplate.update(sql, complaintId, replay, filePhotoPath, user_id); + + updateComplaintStatus(complaintId); + } + + private void updateComplaintStatus(String complaintId) { + String sql = "UPDATE `complaints` SET `status`='close' WHERE id = ?"; + // Execute SQL query to save the photo path related to the category + jdbcSchoolsTemplate.update(sql,complaintId ); + } + //////////////////////////// public List> getAllSubCategories() { String sql = "SELECT * FROM sub_category"; @@ -897,13 +1047,13 @@ public class SchoolUserActivity { + "JOIN category cd ON fb.cat_question_id = cd.id " + "JOIN school_details sd ON fb.school_details_id = sd.id " + "LEFT JOIN school_photos sp ON sd.id = sp.school_details_id " - + "LEFT JOIN category_photos cp ON fb.qid = cp.qid " + + "LEFT JOIN category_photos cp ON fb.qid = cp.qid AND cp.feedref= ? " + "LEFT JOIN category_question cq ON fb.qid = cq.id " + "JOIN school_type st ON st.id = sd.school_type " + "WHERE fb.feedref = ? " + "GROUP BY fb.zone, fb.division, fb.id, sd.school_name, cd.category, sd.school_type, fb.feedback, fb.feedref"; - List> result = jdbcSchoolsTemplate.queryForList(sql,feedref); + List> result = jdbcSchoolsTemplate.queryForList(sql,feedref,feedref); if (result.isEmpty()) { return Collections.emptyMap(); @@ -1024,7 +1174,7 @@ public class SchoolUserActivity { String sampleoffoodmaintainedAns, String cookingstaffwearingQa, String cookingstaffwearingAns, String fooditemsmatchwiththestockQa, String fooditemsmatchwiththestockAns, String fooditemsusedofgoodqualityQa, String fooditemsusedofgoodqualityAns, MultipartFile feedPhoto, - int school_details_id, String zone, String division, Double latitude, double longitude, + int school_details_id, String zone, String division, double latitude, double longitude, String user_id, String question_id) { String feedPhotoPath = null; @@ -1058,6 +1208,75 @@ public class SchoolUserActivity { } } + public void savePlayFields(int categoryId, + String playfieldavailableQa, String playfieldavailableAns, + String civilworkQa, String civilworkAns, + String electricalworkQa, String electricalworkAns, + String sportsmaterialkQa, String sportsmaterialAns, + MultipartFile playfieldPhoto, + MultipartFile civilworkPhoto, + int school_details_id, String zone, String division, double latitude, double longitude, + String user_id, String question_id) { + + String playfieldPhotoPath = null; + String civilworkPhotoPath = null; + + // Handle file upload if a photo is provided + if (playfieldPhoto != null && !playfieldPhoto.isEmpty()) { + // Make sure to pass the correct type for the first argument + String id = String.valueOf(categoryId); + String sdid = String.valueOf(school_details_id); + playfieldPhotoPath = fileUpload(id, sdid, playfieldPhoto); // Adjusted to use schoolDetailsId + } + if (civilworkPhoto != null && !civilworkPhoto.isEmpty()) { + String id = String.valueOf(categoryId); + String sdid = String.valueOf(school_details_id); + civilworkPhotoPath = fileUpload(id, sdid, civilworkPhoto); // Adjusted to use schoolDetailsId + //playgroundPhotoPath = assetFileUpload(categoryId, PlaygroundfeedPhoto, school_details_id); + } + // Create a map for questions and answers + Map questionsAndAnswers = new HashMap<>(); + questionsAndAnswers.put(playfieldavailableQa, playfieldavailableAns); + questionsAndAnswers.put(civilworkQa, civilworkAns); + questionsAndAnswers.put(electricalworkQa, electricalworkAns); + questionsAndAnswers.put(sportsmaterialkQa, sportsmaterialAns); + + String feedref = generateRandomString(); //generate feedback reference text + + // Save feedback for each question and answer pair + questionsAndAnswers.forEach((question, answer) -> + saveFeedbackDetails(categoryId, question, answer, school_details_id, zone, division, latitude, longitude, user_id,feedref) + ); + + // If a photo was uploaded, save it in the category_photos table + if (playfieldPhotoPath != null) { + String qid="59"; + saveCategoryPhoto(categoryId,playfieldPhotoPath,qid,feedref); + } + if (civilworkPhotoPath != null) { + String qid="60"; + saveCategoryPhoto(categoryId,civilworkPhotoPath,qid,feedref); + } + } + + // Complaints List + + public List> getComplaints(String userId) { + String sql = "SELECT `id`, `cid`, `qid`, `feedref`, `school_details_id`, `complaint_txt`, `cdate`, `status`, `user_id` FROM `complaints` WHERE `user_id`=?"; + + List> result = jdbcSchoolsTemplate.queryForList(sql,userId); + return result; + } + + public List> getComplaintsReplay(String comid) { + String sql = "SELECT `id`, `comid`, `replay`, `file`, " + + "CONCAT('"+fileBaseUrl+"/gccofficialapp/files', file) AS photos, " + + "`cby`, `cdate`, `isactive` FROM `complaints_reply` WHERE `comid`=?"; + + List> result = jdbcSchoolsTemplate.queryForList(sql,comid); + return result; + } + } diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/hoardings/controller/APIHoardingsController.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/hoardings/controller/APIHoardingsController.java new file mode 100644 index 0000000..ee97d74 --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/hoardings/controller/APIHoardingsController.java @@ -0,0 +1,297 @@ +package in.gov.chennaicorporation.mobileservice.hoardings.controller; + +import java.util.List; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.util.MultiValueMap; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +import in.gov.chennaicorporation.mobileservice.hoardings.services.HoardingsService; + +@RequestMapping("/gccofficialapp/hoardings/api") +@RestController("apiHoardingsRest") +public class APIHoardingsController { + @Autowired + private HoardingsService hoardingsService; + + + @GetMapping("/licenseVerify") + public List licenseVerify(@RequestParam MultiValueMap formData, + @RequestParam(value = "license_no", required = true) String license_no, + @RequestParam(value = "latitude", required = true) String latitude, + @RequestParam(value = "longitude", required = true) String longitude, + @RequestParam(value = "loginId", required = false) String loginId) { + return hoardingsService.licenseVerify(license_no,latitude,longitude); + } + + @PostMapping(value="/saveHoardings") // Enumeration + public List saveHoardings(@RequestParam MultiValueMap formData, + @RequestParam(value = "categoryId", required = false) String categoryId, + @RequestParam(value = "assetName", required = false) String assetName, + @RequestParam(value = "latitude", required = false) String latitude, + @RequestParam(value = "longitude", required = false) String longitude, + @RequestParam(value = "zone", required = false) String zone, + @RequestParam(value = "ward", required = false) String ward, + @RequestParam(value = "streeId", required = false) String streeId, + @RequestParam(value = "streetName", required = false) String streetName, + @RequestParam(value = "loginId", required = false) String loginId, + @RequestParam(value = "remarks", required = false) String remarks, + @RequestParam(value = "file", required = false) MultipartFile file, + @RequestParam(value = "hoarding_info_type", required = false) String hoarding_info_type, + @RequestParam(value = "lincenses_info", required = false) String lincenses_info, + @RequestParam(value = "lincenses_no", required = false) String lincenses_no, + @RequestParam(value = "validity_date", required = false) String validity_date, + @RequestParam(value = "case_no", required = false) String case_no, + @RequestParam(value = "ptax_no", required = false) String ptax_no, + @RequestParam(value = "ptax_name", required = false) String ptax_name, + @RequestParam(value = "ptax_mobile", required = false) String ptax_mobile, + @RequestParam(value = "agency_name", required = false) String agency_name, + @RequestParam(value = "agency_mobile", required = false) String agency_mobile, + @RequestParam(value = "fine_to", required = false) String fine_to + ) { + return hoardingsService.saveHoardings(formData, categoryId, assetName, latitude, longitude, zone, ward, streeId, + streetName, loginId,remarks,file, + hoarding_info_type, + lincenses_info, + lincenses_no, + validity_date, + case_no, + ptax_no, + ptax_name, + ptax_mobile, + agency_name, + agency_mobile, + fine_to); + } + + @PostMapping(value="/updateHoardingInfo") // Enumeration + public List updateHoardingInfo(@RequestParam MultiValueMap formData, + @RequestParam(value = "loginId", required = true) String loginId, + @RequestParam(value = "asset_id", required = true) String asset_id, + @RequestParam(value = "remarks", required = false) String remarks, + @RequestParam(value = "hoarding_info_type", required = false) String hoarding_info_type, + @RequestParam(value = "lincenses_info", required = false) String lincenses_info, + @RequestParam(value = "lincenses_no", required = false) String lincenses_no, + @RequestParam(value = "validity_date", required = false) String validity_date, + @RequestParam(value = "case_no", required = false) String case_no, + @RequestParam(value = "ptax_no", required = false) String ptax_no, + @RequestParam(value = "ptax_name", required = false) String ptax_name, + @RequestParam(value = "ptax_mobile", required = false) String ptax_mobile, + @RequestParam(value = "agency_name", required = false) String agency_name, + @RequestParam(value = "agency_mobile", required = false) String agency_mobile, + @RequestParam(value = "fine_to", required = false) String fine_to + ) { + return hoardingsService.updateHoardingInfo(formData, + asset_id, + hoarding_info_type, + remarks, + lincenses_info, + lincenses_no, + validity_date, + case_no, + ptax_no, + ptax_name, + ptax_mobile, + agency_name, + agency_mobile, + fine_to, + loginId); + } + + + + + @GetMapping("/assetlist") + public List assetlist(@RequestParam MultiValueMap formData, + @RequestParam(value = "loginId", required = false) String loginId) { + return hoardingsService.assetlist(formData,loginId); + } + + @GetMapping("/assetlistbylogin") + public List assetlistbylogin(@RequestParam MultiValueMap formData, + @RequestParam(value = "loginId", required = true) String loginId) { + return hoardingsService.assetlistbylogin(formData,loginId); + } + + @GetMapping("/assetlistbylatlong") + public List assetlistbylatlong(@RequestParam MultiValueMap formData, + @RequestParam(value = "latitude", required = true) String latitude, + @RequestParam(value = "longitude", required = true) String longitude, + @RequestParam(value = "loginId", required = false) String loginId) { + return hoardingsService.assetlistbylatlong(formData, latitude, longitude,loginId); + } + + @GetMapping("/getChallanPOSData") + public List getChallanPOSData(@RequestParam MultiValueMap formData, + @RequestParam(value = "orderid", required = false) String orderid, + @RequestParam(value = "loginid", required = true) String loginid) { + return hoardingsService.getChallanPOSData(formData,orderid,loginid); + } + + @GetMapping("/updateSerialNumber") + public List updateSerialNumber(@RequestParam MultiValueMap formData, + @RequestParam(value = "tid", required = true) String tid, + @RequestParam(value = "mid", required = true) String mid, + @RequestParam(value = "serialNumber", required = true) String serialNumber, + @RequestParam(value = "orderid", required = true) String orderid) { + return hoardingsService.updateSerialNumber(formData,tid, mid, serialNumber, orderid); + } + + @PostMapping("/storeBankTransaction") + public List storeBankTransaction(@RequestBody Map transactionData) { + return hoardingsService.storeBankTransaction(transactionData); + } + + @PostMapping("/storeFailedBankTransaction") + public List storeFailedBankTransaction(@RequestBody Map transactionData) { + return hoardingsService.storeFailedBankTransaction(transactionData); + } + + @PostMapping(value="/updateHoardings") // Enumeration + public List insertHoardingUpdatedData(@RequestParam MultiValueMap formData, + @RequestParam(value = "asset_id", required = false) String asset_id, + @RequestParam(value = "update_type", required = false) String update_type, + @RequestParam(value = "removed_type", required = false) String removed_type, + @RequestParam(value = "file", required = false) MultipartFile file, + @RequestParam(value = "licenses_no_visible", required = false) String licenses_no_visible, + @RequestParam(value = "validity_date_visible", required = false) String validity_date_visible, + @RequestParam(value = "not_as_per_size", required = false) String not_as_per_size, + @RequestParam(value = "licenses_no", required = false) String licenses_no, + @RequestParam(value = "loginId", required = false) String loginId + ) { + return hoardingsService.insertHoardingUpdatedData(formData, + asset_id, + update_type, + removed_type, + file, + licenses_no_visible, + validity_date_visible, + not_as_per_size, + licenses_no, + loginId); + } + + @GetMapping("/unauterrizedassetlistbylogin") + public List unAuterrizedAssetlist(@RequestParam MultiValueMap formData, + @RequestParam(value = "loginId", required = true) String loginId) { + return hoardingsService.unAuterrizedAssetlist(formData,loginId); + } + + @GetMapping("/unauterrizedassetlistbylatlong") + public List assetlistbylatlong(@RequestParam MultiValueMap formData, + @RequestParam(value = "latitude", required = true) String latitude, + @RequestParam(value = "longitude", required = true) String longitude, + @RequestParam(value = "assetid", required = false) String assetid, + @RequestParam(value = "loginId", required = false) String loginId) { + return hoardingsService.unauterrizedassetlistbylatlong(formData, latitude, longitude, assetid, loginId); + } + + @PostMapping(value="/updateHoardingsAE") // Enumeration + public List insertHoardingUpdatedDataAE(@RequestParam MultiValueMap formData, + @RequestParam(value = "asset_id", required = false) String asset_id, + @RequestParam(value = "remarks", required = false) String remarks, + @RequestParam(value = "removed_type", required = false) String removed_type, + @RequestParam(value = "file", required = false) MultipartFile file, + //@RequestParam(value = "firfile", required = false) MultipartFile firfile, + //@RequestParam(value = "fir", required = false) String fir, + //@RequestParam(value = "fir_number", required = false) String fir_number, + //@RequestParam(value = "material_collected", required = false) String material_collected, + //@RequestParam(value = "materialfile", required = false) MultipartFile materialfile, + @RequestParam(value = "loginId", required = false) String loginId + ) { + return hoardingsService.insertHoardingUpdatedDataAE(formData, + asset_id, + remarks, + removed_type, + file, + //firfile, + //fir, + //fir_number, + //material_collected, + //materialfile, + loginId); + } + + @PostMapping(value="/updateMaterialInfo") // Enumeration + public List updateMaterialInfo(@RequestParam MultiValueMap formData, + @RequestParam(value = "id", required = true) String id, + @RequestParam(value = "asset_id", required = true) String asset_id, + @RequestParam(value = "material_collected", required = false) String material_collected, + @RequestParam(value = "material_remarks", required = false) String material_remarks, + @RequestParam(value = "materialfile", required = false) MultipartFile materialfile, + @RequestParam(value = "loginId", required = false) String loginId + ) { + return hoardingsService.updateMaterialInfo( + id, + asset_id, + material_collected, + material_remarks, + materialfile); + } + + @PostMapping(value="/updateFirInfo") // Enumeration + public List updateFirInfo(@RequestParam MultiValueMap formData, + @RequestParam(value = "id", required = true) String id, + @RequestParam(value = "asset_id", required = true) String asset_id, + @RequestParam(value = "firfile", required = false) MultipartFile firfile, + @RequestParam(value = "fir_number", required = false) String fir_number, + @RequestParam(value = "fir_remarks", required = false) String fir_remarks, + @RequestParam(value = "loginId", required = false) String loginId + ) { + return hoardingsService.updateFirInfo( + id, + asset_id, + fir_number, + fir_remarks, + firfile); + } + + @GetMapping("/unAuterrizedAssetlistAEPending") + public List unAuterrizedAssetlistAEPending(@RequestParam MultiValueMap formData, + @RequestParam(value = "pendingType", required = true) String pendingType, + @RequestParam(value = "loginId", required = true) String loginId) { + return hoardingsService.unAuterrizedAssetlistAEPending(formData, pendingType, loginId); + } + + @GetMapping("/ReportTile") + public List ReportTile(@RequestParam MultiValueMap formData, + @RequestParam(value = "fromDate", required = true) String fromDate, + @RequestParam(value = "toDate", required = true) String toDate, + @RequestParam(value = "loginId", required = false) String loginId) { + return hoardingsService.ReportTile(fromDate, toDate); + } + + @GetMapping("/reportZoneList") + public List reportZoneList(@RequestParam MultiValueMap formData, + @RequestParam(value = "fromDate", required = true) String fromDate, + @RequestParam(value = "toDate", required = true) String toDate, + @RequestParam(value = "loginId", required = false) String loginId) { + return hoardingsService.reportZoneList(fromDate, toDate); + } + + @GetMapping("/reportWardList") + public List reportZoneList(@RequestParam MultiValueMap formData, + @RequestParam(value = "zone", required = true) String zone, + @RequestParam(value = "fromDate", required = true) String fromDate, + @RequestParam(value = "toDate", required = true) String toDate, + @RequestParam(value = "loginId", required = false) String loginId) { + return hoardingsService.reportWardList(zone, fromDate, toDate); + } + + @GetMapping("/reportListBySelect") + public List reportZoneList(@RequestParam MultiValueMap formData, + @RequestParam(value = "ward", required = true) String ward, + @RequestParam(value = "hoarding_info_type", required = true) String hoarding_info_type, + @RequestParam(value = "fromDate", required = true) String fromDate, + @RequestParam(value = "toDate", required = true) String toDate, + @RequestParam(value = "loginId", required = false) String loginId) { + return hoardingsService.reportListBySelect(ward, hoarding_info_type, fromDate, toDate); + } +} diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/hoardings/controller/package-info.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/hoardings/controller/package-info.java new file mode 100644 index 0000000..2a4bd0c --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/hoardings/controller/package-info.java @@ -0,0 +1 @@ +package in.gov.chennaicorporation.mobileservice.hoardings.controller; \ No newline at end of file diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/hoardings/package-info.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/hoardings/package-info.java new file mode 100644 index 0000000..784d1a9 --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/hoardings/package-info.java @@ -0,0 +1 @@ +package in.gov.chennaicorporation.mobileservice.hoardings; \ No newline at end of file diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/hoardings/services/HoardingsService.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/hoardings/services/HoardingsService.java new file mode 100644 index 0000000..7c512f7 --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/hoardings/services/HoardingsService.java @@ -0,0 +1,1956 @@ +package in.gov.chennaicorporation.mobileservice.hoardings.services; + +import java.awt.image.BufferedImage; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.SecureRandom; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; + +import javax.imageio.ImageIO; +import javax.imageio.ImageWriteParam; +import javax.imageio.ImageWriter; +import javax.imageio.stream.ImageOutputStream; +import javax.sql.DataSource; + +import org.hibernate.internal.build.AllowSysOut; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.core.env.Environment; +import org.springframework.dao.DataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.PreparedStatementCreator; +import org.springframework.jdbc.support.GeneratedKeyHolder; +import org.springframework.jdbc.support.KeyHolder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.MultiValueMap; +import org.springframework.web.multipart.MultipartFile; + +import in.gov.chennaicorporation.mobileservice.gccactivity.service.DateTimeUtil; + +@Service +public class HoardingsService { + private JdbcTemplate jdbcHoardingsTemplate; + private final Environment environment; + private String fileBaseUrl; + + private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + private static final int STRING_LENGTH = 15; + private static final Random RANDOM = new SecureRandom(); + + @Autowired + public void setDataSource(@Qualifier("mysqlHoardingsDataSource") DataSource hoardings) { + this.jdbcHoardingsTemplate = new JdbcTemplate(hoardings); + } + + @Autowired + public HoardingsService(Environment environment) { + this.environment = environment; + this.fileBaseUrl=environment.getProperty("fileBaseUrl"); + } + + 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(); + } + + // Function to convert date string from dd-MM-yyyy to yyyy-MM-dd + public static String convertDateFormat(String inputDate, int add) { + // Check if the inputDate is not null or blank + if (inputDate != null && !inputDate.isBlank()) { + try { + // Define the input and output date formats + DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + + // Parse the input date string to LocalDate + LocalDate date = LocalDate.parse(inputDate, inputFormatter); + + // Add the specified number of days to the date if 'add' is greater than 0 + if (add > 0) { + date = date.plusDays(add); + } + + // Format the date to the new format + return date.format(outputFormatter); + + } catch (DateTimeParseException e) { + // Handle the case where the input date is invalid + System.out.println("Invalid date format: " + inputDate); + return ""; + } + } else { + return ""; + } + } + + private byte[] compressImage(BufferedImage image, float quality) throws IOException { + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(byteArrayOutputStream); + + ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next(); + writer.setOutput(imageOutputStream); + + 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.dispose(); + imageOutputStream.close(); + + return byteArrayOutputStream.toByteArray(); + } + + public String fileUpload(String name, String id, String folder, 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("hoardings_foldername"); + var year =DateTimeUtil.getCurrentYear(); + var month =DateTimeUtil.getCurrentMonth(); + + uploadDirectory = uploadDirectory + serviceFolderName + year +"/"+month+"/"+folder+"/"; + + 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 + String fileName = name+ "_" +id + "_" + datetimetxt + "_" + file.getOriginalFilename(); + fileName = fileName.replaceAll("\\s+", ""); // Remove space on filename + + String filePath = uploadDirectory + "/" + fileName; + + String filepath_txt = "/"+serviceFolderName + year +"/"+month+"/"+folder+"/"+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, compressedBytes); + + System.out.println(filePath); + return filepath_txt; + + } catch (IOException e) { + e.printStackTrace(); + return "Failed to save file " + file.getOriginalFilename(); + } + } + + /* + @Transactional + public List> licenseVerify( + String license_no, + String latitude, + String longitude) { + + String sqlQuery = "SELECT `id`, `name`, `mobile`, `license_no`, `latitude`, `longitude`, `valid_from`, `valid_to`, " + + "CONCAT(DATE_FORMAT(`valid_from`, '%d-%m-%Y'), ' to ' , DATE_FORMAT(`valid_to`, '%d-%m-%Y')) AS valid_date " + + "FROM `hoarding_license` WHERE " + + "`license_no`=? AND ((6371008.8 * acos(ROUND(cos(radians(" + latitude + + ")) * cos(radians(latitude)) * cos(radians(longitude) - radians(" + longitude + + ")) + sin(radians(" + latitude + ")) * sin(radians(latitude)), 9))) < 500)"; + + List> result = jdbcHoardingsTemplate.queryForList(sqlQuery, license_no); + Map response = new HashMap<>(); + response.put("status", 200); + response.put("message", "License Data"); + response.put("data", result); + + return Collections.singletonList(response); + } + */ + @Transactional + public List> licenseVerify( + String license_no, + String latitude, + String longitude) { + + String sqlQuery = "SELECT `id`, `name`, `mobile`, `license_no`, `latitude`, `longitude`, `valid_from`, `valid_to`, " + + "CONCAT(DATE_FORMAT(`valid_from`, '%d-%m-%Y'), ' to ' , DATE_FORMAT(`valid_to`, '%d-%m-%Y')) AS valid_date " + + "FROM `hoarding_license` WHERE " + + "`license_no`=? AND `gcc_app_updated`=0"; + //+ "AND ((6371008.8 * acos(ROUND(cos(radians(" + latitude + //+ ")) * cos(radians(latitude)) * cos(radians(longitude) - radians(" + longitude + //+ ")) + sin(radians(" + latitude + ")) * sin(radians(latitude)), 9))) < 500)"; + + List> result = jdbcHoardingsTemplate.queryForList(sqlQuery, license_no); + Map response = new HashMap<>(); + response.put("status", 200); + response.put("message", "License Data"); + response.put("data", result); + + return Collections.singletonList(response); + } + + private void updateHoardingLicenseInactive(String license_no, int asset_id) { + String sql = "UPDATE `hoarding_license` SET `gcc_app_updated`=? WHERE `license_no`=?"; + jdbcHoardingsTemplate.update(sql, asset_id, license_no); + } + + @Transactional + public List> saveHoardings( + MultiValueMap formData, + String category_id, + String assetName, + String latitude, + String longitude, + String zone, + String ward, + String streeId, + String streetName, + String loginId, + String remarks, + MultipartFile file, + String hitid, + String licenses_info, + String licenses_no, + String validity_date, + String case_no, + String ptax_no, + String ptax_name, + String ptax_mobile, + String agency_name, + String agency_mobile, + String fine_to) { + + Map response = new HashMap<>(); + int lastInsertId = 0; + if(hitid.equals('1')) { + // Check if the licenses_no exists in hoardings_info table + String checkLicensesQuery = "SELECT COUNT(*) FROM hoardings_info WHERE licenses_no = ?"; + int count = jdbcHoardingsTemplate.queryForObject(checkLicensesQuery, Integer.class, licenses_no); + + if (count > 0) { + // If the licenses_no exists, return an error message + response.put("status", "error"); + response.put("message", "Licenses No already exists!."); + return Collections.singletonList(response); + } + } + + String image = fileUpload("hoarding_asset",category_id,"asset",file); + + String sqlQuery = "INSERT INTO `asset_list`(`category_id`, `image`, `latitude`, `longitude`, " + + "`zone`, `ward`, `streetid`, `streetname`, `cby`,`remarks`,`name`) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?)"; + + KeyHolder keyHolder = new GeneratedKeyHolder(); + + try { + int affectedRows = jdbcHoardingsTemplate.update(new PreparedStatementCreator() { + @Override + public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { + PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[]{"id"}); + ps.setString(1, category_id); + ps.setString(2, image); + ps.setString(3, latitude); + ps.setString(4, longitude); + ps.setString(5, zone); + ps.setString(6, ward); + ps.setString(7, streeId); + ps.setString(8, streetName); + ps.setString(9, loginId); + ps.setString(10, remarks); + ps.setString(11, assetName); + return ps; + } + }, keyHolder); + + if (affectedRows > 0) { + Number generatedId = keyHolder.getKey(); + lastInsertId = (generatedId != null) ? generatedId.intValue() : 0; + int asset_id = lastInsertId; + response.put("insertId", lastInsertId); + response.put("status", "success"); + response.put("message", "New Hoardings added successfully!"); + System.out.println("New Hoardings added successfully! Insert ID: " + generatedId); + System.out.println("test:"+case_no); + + updateHoardingLicenseInactive(licenses_no,asset_id); + + int getUpdateStatus=insertHoardingInfo( + asset_id, + hitid, + remarks, + licenses_info, + licenses_no, + validity_date, + case_no, + ptax_no, + ptax_name, + ptax_mobile, + agency_name, + agency_mobile, + fine_to, + loginId); + + } else { + response.put("status", "error"); + response.put("message", "Failed to insert a new hoardings (Asset)."); + } + } catch (DataAccessException e) { + System.out.println("Data Access Exception:"); + Throwable rootCause = e.getMostSpecificCause(); + if (rootCause instanceof SQLException) { + SQLException sqlException = (SQLException) rootCause; + System.out.println("SQL State: " + sqlException.getSQLState()); + System.out.println("Error Code: " + sqlException.getErrorCode()); + System.out.println("Message: " + sqlException.getMessage()); + response.put("status", "error"); + response.put("message", sqlException.getMessage()); + response.put("sqlState", sqlException.getSQLState()); + response.put("errorCode", sqlException.getErrorCode()); + } else { + System.out.println("Message: " + rootCause.getMessage()); + response.put("status", "error"); + response.put("message", rootCause.getMessage()); + } + } + + return Collections.singletonList(response); + } + + public Integer insertHoardingInfo( + int asset_id, + String hitid, + String remarks, + String licenses_info, + String licenses_no, + String validity_date, + String case_no, + String ptax_no, + String ptax_name, + String ptax_mobile, + String agency_name, + String agency_mobile, + String fine_to, + String cby) { + String sqlQuery = "INSERT INTO `hoardings_info`(`asset_id`, `hitid`, `remarks`, `licenses_info`, " + + "`licenses_no`, `validity_date`, `case_no`, `ptax_no`, `ptax_name`, `ptax_mobile`, " + + "`agency_name`, `agency_mobile`, `fine_to`, `cby`) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + + Map response = new HashMap<>(); + int lastInsertId = 0; + String status="error"; + KeyHolder keyHolder = new GeneratedKeyHolder(); + + try { + int affectedRows = jdbcHoardingsTemplate.update(new PreparedStatementCreator() { + @Override + public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { + PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[]{"id"}); + ps.setInt(1, asset_id); + ps.setString(2, hitid); + ps.setString(3, remarks); + ps.setString(4, licenses_info); + ps.setString(5, licenses_no); + ps.setString(6, validity_date); + ps.setString(7, case_no); + ps.setString(8, ptax_no); + ps.setString(9, ptax_name); + ps.setString(10, ptax_mobile); + ps.setString(11, agency_name); + ps.setString(12, agency_mobile); + ps.setString(13, fine_to); + ps.setString(14, cby); + return ps; + } + }, keyHolder); + + if (affectedRows > 0) { + Number generatedId = keyHolder.getKey(); + lastInsertId = (generatedId != null) ? generatedId.intValue() : 0; + response.put("insertId", lastInsertId); + response.put("status", "success"); + response.put("message", "New Hoardings Info added successfully!"); + System.out.println("New Hoardings Info added successfully! Insert ID: " + generatedId); + + // Generate Challan and store (Update in info table) if hitid==3 (UnAuterized) + if("3".equals(hitid)) { + createChallan(lastInsertId, "Challan created", hitid); + } + + } else { + response.put("status", "error"); + response.put("message", "Failed to insert a new hoardings Info (Info)."); + } + } catch (DataAccessException e) { + System.out.println("Data Access Exception:"); + Throwable rootCause = e.getMostSpecificCause(); + if (rootCause instanceof SQLException) { + SQLException sqlException = (SQLException) rootCause; + System.out.println("SQL State: " + sqlException.getSQLState()); + System.out.println("Error Code: " + sqlException.getErrorCode()); + System.out.println("Message: " + sqlException.getMessage()); + response.put("status", "error"); + response.put("message", sqlException.getMessage()); + response.put("sqlState", sqlException.getSQLState()); + response.put("errorCode", sqlException.getErrorCode()); + } else { + System.out.println("Message: " + rootCause.getMessage()); + response.put("status", "error"); + response.put("message", rootCause.getMessage()); + } + } + + return lastInsertId; + } + + /* ============= Update Hoardings ============= */ + private String deleteOldHoardingInfo(String asset_id, String cby) { + String sqlQuery ="INSERT INTO `hoardings_info_trash` " + + " ( `id`, " + + " `asset_id`, " + + " `hitid`, " + + " `remarks`, " + + " `licenses_info`, " + + " `licenses_no`, " + + " `validity_date`, " + + " `case_no`, " + + " `ptax_no`, " + + " `ptax_name`, " + + " `ptax_mobile`, " + + " `agency_name`, " + + " `agency_mobile`, " + + " `fine_to`, " + + " `fine_amount`, " + + " `fine_status`, " + + " `orderid`, " + + " `cdate`, " + + " `cby`, " + + " `tid`, " + + " `mid`, " + + " `serial_number`, " + + " `isactive`, " + //+ " `trash_date`, " + + " `trash_by` " + + " ) " + + " SELECT `id`," + + " `asset_id`, " + + " `hitid`, " + + " `remarks`, " + + " `licenses_info`, " + + " `licenses_no`, " + + " `validity_date`, " + + " `case_no`, " + + " `ptax_no`, " + + " `ptax_name`, " + + " `ptax_mobile`, " + + " `agency_name`, " + + " `agency_mobile`, " + + " `fine_to`, " + + " `fine_amount`, " + + " `fine_status`, " + + " `orderid`, " + + " `cdate`, " + + " `cby`, " + + " `tid`, " + + " `mid`, " + + " `serial_number`, " + + " `isactive`, " + //+ " NOW() AS `trash_date`, " + + " ? AS `trash_by` " + + " FROM " + + " `hoardings_info` " + + " WHERE " + + " `asset_id` = ?"; + int lastInsertId = 0; + String status="error"; + KeyHolder keyHolder = new GeneratedKeyHolder(); + + try { + int affectedRows = jdbcHoardingsTemplate.update(new PreparedStatementCreator() { + @Override + public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { + PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[]{"id"}); + ps.setString(1, cby); + ps.setString(2, asset_id); + return ps; + } + }, keyHolder); + + if (affectedRows > 0) { + Number generatedId = keyHolder.getKey(); + lastInsertId = (generatedId != null) ? generatedId.intValue() : 0; + + String sqlDelete = "DELETE FROM `hoardings_info` WHERE `asset_id` = ?"; + // Delete the original data + jdbcHoardingsTemplate.update(sqlDelete, asset_id); + + return "success"; + + } else { + return "error"; + } + } catch (DataAccessException e) { + System.out.println("Data Access Exception:"); + Throwable rootCause = e.getMostSpecificCause(); + if (rootCause instanceof SQLException) { + SQLException sqlException = (SQLException) rootCause; + System.out.println("SQL State: " + sqlException.getSQLState()); + System.out.println("Error Code: " + sqlException.getErrorCode()); + System.out.println("Message: " + sqlException.getMessage()); + return "error"; + } else { + return "error"; + } + } + //return "success"; + } + + public List> updateHoardingInfo( + MultiValueMap formData, + String asset_id, + String hitid, + String remarks, + String licenses_info, + String licenses_no, + String validity_date, + String case_no, + String ptax_no, + String ptax_name, + String ptax_mobile, + String agency_name, + String agency_mobile, + String fine_to, + String cby) { + + Map response = new HashMap<>(); + + if(hitid.equals('1')) { + // Check if the licenses_no exists in hoardings_info table + String checkLicensesQuery = "SELECT COUNT(*) FROM hoardings_info WHERE licenses_no = ? AND `asset_id` <> ?"; + int count = jdbcHoardingsTemplate.queryForObject(checkLicensesQuery, Integer.class, licenses_no, asset_id); + + if (count > 0) { + // If the licenses_no exists, return an error message + response.put("status", "error"); + response.put("message", "Licenses No already exists!."); + return Collections.singletonList(response); + } + } + + String queryStatus = deleteOldHoardingInfo(asset_id, cby); // Delete old Hoarding Info data + + if(queryStatus.equals("success")){ + String sqlQuery = "INSERT INTO `hoardings_info`(`asset_id`, `hitid`, `remarks`, `licenses_info`, " + + "`licenses_no`, `validity_date`, `case_no`, `ptax_no`, `ptax_name`, `ptax_mobile`, " + + "`agency_name`, `agency_mobile`, `fine_to`, `cby`) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + + + int lastInsertId = 0; + String status="error"; + KeyHolder keyHolder = new GeneratedKeyHolder(); + + try { + int affectedRows = jdbcHoardingsTemplate.update(new PreparedStatementCreator() { + @Override + public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { + PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[]{"id"}); + ps.setString(1, asset_id); + ps.setString(2, hitid); + ps.setString(3, remarks); + ps.setString(4, licenses_info); + ps.setString(5, licenses_no); + ps.setString(6, validity_date); + ps.setString(7, case_no); + ps.setString(8, ptax_no); + ps.setString(9, ptax_name); + ps.setString(10, ptax_mobile); + ps.setString(11, agency_name); + ps.setString(12, agency_mobile); + ps.setString(13, fine_to); + ps.setString(14, cby); + return ps; + } + }, keyHolder); + + if (affectedRows > 0) { + Number generatedId = keyHolder.getKey(); + lastInsertId = (generatedId != null) ? generatedId.intValue() : 0; + response.put("insertId", lastInsertId); + response.put("status", "success"); + response.put("message", "New Hoardings Info added successfully!"); + System.out.println("New Hoardings Info added successfully! Insert ID: " + generatedId); + + // Generate Challan and store (Update in info table) if hitid==3 (UnAuterized) + if("3".equals(hitid)) { + createChallan(lastInsertId, "Challan created", hitid); + } + + } else { + response.put("status", "error"); + response.put("message", "Failed to insert a new hoardings Info (Info)."); + } + } catch (DataAccessException e) { + System.out.println("Data Access Exception:"); + Throwable rootCause = e.getMostSpecificCause(); + if (rootCause instanceof SQLException) { + SQLException sqlException = (SQLException) rootCause; + System.out.println("SQL State: " + sqlException.getSQLState()); + System.out.println("Error Code: " + sqlException.getErrorCode()); + System.out.println("Message: " + sqlException.getMessage()); + response.put("status", "error"); + response.put("message", sqlException.getMessage()); + response.put("sqlState", sqlException.getSQLState()); + response.put("errorCode", sqlException.getErrorCode()); + } else { + System.out.println("Message: " + rootCause.getMessage()); + response.put("status", "error"); + response.put("message", rootCause.getMessage()); + } + } + } + else { + System.out.println("Message DELETE ID: " + asset_id + " "+ queryStatus); + response.put("status", "error"); + response.put("message", "Hoding Info Delete failed :" + asset_id + " "+ queryStatus); + } + + return Collections.singletonList(response); + } + + /* ============= End Update ================ */ + + public String createChallan(int id, String status, String hitid) { + // Fetch the fine details as a list of maps + List> fineAmountList = getFineAmount("1"); + + if (fineAmountList != null && !fineAmountList.isEmpty()) { + // Extract the first map from the list (it's wrapped in a 'data' key) + Map response = fineAmountList.get(0); + + // Extract the data list from the 'data' key + List> fineAmountDataList = (List>) response.get("data"); + + if (fineAmountDataList != null && !fineAmountDataList.isEmpty()) { + // Extract the first record (since we expect only one record as per the query) + Map fineAmountData = fineAmountDataList.get(0); + + // Safely get the fine amount, and check if it's null + Object fineAmountObj = fineAmountData.get("amount"); + if (fineAmountObj != null) { + // Convert to String only if not null + String fineAmountValue = fineAmountObj.toString(); // Fetch the amount + String fineStatus = status; // Use the passed status for updating + + // Update the hoardings_info table with fine amount and status + String sqlQuery = "UPDATE `hoardings_info` SET `fine_amount` = ?, `fine_status` = ?, `orderid` = ? WHERE id=? LIMIT 1"; + String orderid = generateRandomString(); + jdbcHoardingsTemplate.update(sqlQuery, fineAmountValue, fineStatus, orderid, id); + System.out.println("UPDATE `hoardings_info` SET `fine_amount` = "+fineAmountValue+", `fine_status` = "+fineStatus+", `orderid` = "+orderid+" WHERE id="+id+" LIMIT 1"); + return "success"; // Return success after update + } else { + // Handle the case when amount is null + System.out.println("failure: fine amount is null"); + return "failure: fine amount is null"; + } + } else { + // Handle case when data list is empty or not found + System.out.println("failure: no fine amount data found"); + return "failure: no fine amount data found"; + } + } else { + // Handle case when fineAmountList is empty + System.out.println("failure: no fine amount list found"); + return "failure: no fine amount list found"; + } + } + + public String createChallanbyAssetId(int id, String status, String hitid) { + // Fetch the fine details as a list of maps + List> fineAmountList = getFineAmount("1"); + + if (fineAmountList != null && !fineAmountList.isEmpty()) { + // Extract the first map from the list (it's wrapped in a 'data' key) + Map response = fineAmountList.get(0); + + // Extract the data list from the 'data' key + List> fineAmountDataList = (List>) response.get("data"); + + if (fineAmountDataList != null && !fineAmountDataList.isEmpty()) { + // Extract the first record (since we expect only one record as per the query) + Map fineAmountData = fineAmountDataList.get(0); + + // Safely get the fine amount, and check if it's null + Object fineAmountObj = fineAmountData.get("amount"); + if (fineAmountObj != null) { + // Convert to String only if not null + String fineAmountValue = fineAmountObj.toString(); // Fetch the amount + String fineStatus = status; // Use the passed status for updating + + // Update the hoardings_info table with fine amount and status + String sqlQuery = "UPDATE `hoardings_info` SET `fine_amount` = ?, `fine_status` = ?, `orderid` = ? WHERE `asset_id`=? LIMIT 1"; + String orderid = generateRandomString(); + jdbcHoardingsTemplate.update(sqlQuery, fineAmountValue, fineStatus, orderid, id); + return "success"; // Return success after update + } else { + // Handle the case when amount is null + return "failure: fine amount is null"; + } + } else { + // Handle case when data list is empty or not found + return "failure: no fine amount data found"; + } + } else { + // Handle case when fineAmountList is empty + return "failure: no fine amount list found"; + } + } + + public List> getFineAmount(String category_id) { + // SQL query to fetch `id`, `category_id`, `ton`, and `amount` + String sqlQuery = "SELECT `id`, `category_id`, `ton`, `amount` FROM `penalty_amount` " + + "WHERE `category_id`= ? AND `isactive`=1 AND `isdelete`=0 LIMIT 1"; + System.out.println(sqlQuery + category_id); + // Fetching the data and returning as a simple array + List> result = jdbcHoardingsTemplate.queryForList(sqlQuery,category_id); + Map response = new HashMap<>(); + response.put("status", 200); + response.put("message", "Hoarding Fine Amount"); + response.put("data", result); + return Collections.singletonList(response); + } + + @Transactional + public List> assetlist( + MultiValueMap formData, + String loginid) { + + String sqlQuery = "SELECT *, " + + "CONCAT('"+fileBaseUrl+"/gccofficialapp/files',`image`) as imageurl " + + " From `asset_list` WHERE (`isactive`=1 AND `isdelete`=0)"; + + List> result = jdbcHoardingsTemplate.queryForList(sqlQuery); + Map response = new HashMap<>(); + response.put("status", 200); + response.put("message", "Hoarding list"); + response.put("data", result); + + return Collections.singletonList(response); + } + + @Transactional + public List> assetlistbylogin( + MultiValueMap formData, + String loginid) { + /* + String sqlQuery = "SELECT al.`id`, al.`category_id`, ac.`name` category_name, al.`name`, al.`image`, al.`latitude`, " + + "al.`longitude`, al.`zone`, al.`ward`, al.`streetid`, al.`streetname`, al.`cdate`, al.`cby`, al.`remarks`, " + + "hi.`hitid`, hi.`licenses_info`, hi.`licenses_no`, hi.`validity_date`, hi.`case_no`, " + + "hi.`ptax_no`, hi.`ptax_name`, hi.`ptax_mobile`, hi.`agency_name`, hi.`agency_mobile`, hi.`fine_to`, " + + "hit.`name` hoarding_info_type, " + + "CONCAT('"+fileBaseUrl+"/gccofficialapp/files', al.`image`) as imageurl " + + "FROM `asset_list` al " + + "INNER JOIN `hoardings_info` hi ON al.id = hi.asset_id " + + "INNER JOIN `asset_category` ac ON ac.id = al.category_id " + + "INNER JOIN `hoarding_info_type` hit ON hit.id = hi.hitid " + + "WHERE al.`isactive` = 1 AND al.`isdelete` = 0 AND al.`cby` = ?"; + */ + String sqlQuery = "SELECT " + + " al.`id`, " + + " al.`category_id`, " + + " ac.`name` AS category_name, " + + " al.`name`, " + + " al.`image`, " + + " al.`latitude`, " + + " al.`longitude`, " + + " al.`zone`, " + + " al.`ward`, " + + " al.`streetid`, " + + " al.`streetname`, " + + " al.`cdate`, " + + " al.`cby`, " + + " al.`remarks`, " + + " hi.`hitid`, " + + " hi.`licenses_info`, " + + " hi.`licenses_no`, " + + " hi.`validity_date`, " + + " hi.`case_no`, " + + " hi.`ptax_no`, " + + " hi.`ptax_name`, " + + " hi.`ptax_mobile`, " + + " hi.`agency_name`, " + + " hi.`agency_mobile`, " + + " hi.`fine_to`, " + + " hi.`fine_amount`, " + + " hi.`fine_status`, " + + " hi.`orderid`, " + + " hi.`cdate` as ae_cdate, " + + " hi.`cby` as ae_cby, " + + " hi.`tid`, " + + " hi.`mid`, " + + " hi.`serial_number`, " + + " hit.`name` AS hoarding_info_type, " + + " CONCAT('https://gccservices.in/gccofficialapp/files', al.`image`) AS imageurl, " + + " haeu.`update_image`, " + + " haeu.`remarks`, " + + " haeu.`removed_type`, " + + " haeu.`fir`, " + + " haeu.`fir_number`, " + + " haeu.`fir_image`, " + + " haeu.`material_collected`, " + + " haeu.`material_receipt`, " + + " haeu.`cdate` AS ae_cdate, " + + " haeu.`cby` AS ae_cby, " + + " haeu.`material_pending`, " + + " haeu.`fir_pending`, " + + " haeu.`id` AS ae_data_id, " + + " CONCAT('https://gccservices.in/gccofficialapp/files', haeu.`update_image`) AS ae_update_imageurl, " + + " CONCAT('https://gccservices.in/gccofficialapp/files', haeu.`material_receipt`) AS ae_material_imageurl, " + + " CONCAT('https://gccservices.in/gccofficialapp/files', haeu.`fir_image`) AS ae_fir_imageurl " + + "FROM " + + " `asset_list` al " + + "LEFT JOIN " + + " `hoardings_info` hi ON al.id = hi.asset_id " + + "LEFT JOIN " + + " `asset_category` ac ON ac.id = al.category_id " + + "LEFT JOIN " + + " `hoarding_info_type` hit ON hit.id = hi.hitid " + + "LEFT JOIN " + + " `hoarding_ae_update` haeu ON haeu.asset_id = hi.asset_id " + + "WHERE " + + " al.`isactive` = 1 " + + " AND al.`isdelete` = 0 " + + " AND al.`cby` = ? " + + "GROUP BY " + + " al.`id` " + + "ORDER BY" + + " al.`id` DESC"; + + List> result = jdbcHoardingsTemplate.queryForList(sqlQuery,loginid); + Map response = new HashMap<>(); + response.put("status", 200); + response.put("message", "Hoarding list By Login"); + response.put("data", result); + + return Collections.singletonList(response); + } + + + @Transactional + public List> assetlistbylatlong( + MultiValueMap formData, + String latitude, + String longitude, + String loginid) { + + String sqlWhere = ""; + + if (latitude != null && longitude != null && !latitude.isBlank() && !latitude.isEmpty() && !longitude.isBlank() + && !longitude.isEmpty()) { + sqlWhere += " AND ((6371008.8 * acos(ROUND(cos(radians(" + latitude + + ")) * cos(radians(al.latitude)) * cos(radians(al.longitude) - radians(" + longitude + + ")) + sin(radians(" + latitude + ")) * sin(radians(al.latitude)), 9))) < 500)" + + " ORDER BY" + + " al.`id` DESC"; + } + + String sqlQuery = "SELECT al.`id`, al.`category_id`, ac.`name` AS category_name, al.`name`, al.`image`, al.`latitude`, " + + "al.`longitude`, al.`zone`, al.`ward`, al.`streetid`, al.`streetname`, al.`cdate`, al.`cby`, al.`remarks`, " + + "hi.`hitid`, hi.`licenses_info`, hi.`licenses_no`, hi.`validity_date`, hi.`case_no`, " + + "hi.`ptax_no`, hi.`ptax_name`, hi.`ptax_mobile`, hi.`agency_name`, hi.`agency_mobile`, hi.`fine_to`, " + + "hit.`name` AS hoarding_info_type, " + + "CONCAT('"+fileBaseUrl+"/gccofficialapp/files', al.`image`) AS imageurl " + + "FROM `asset_list` al " + + "INNER JOIN `hoardings_info` hi ON al.id = hi.asset_id " + + "INNER JOIN `asset_category` ac ON ac.id = al.category_id " + + "INNER JOIN `hoarding_info_type` hit ON hit.id = hi.hitid " + + "WHERE al.`isactive` = 1 AND al.`isdelete` = 0" // This is the starting part of WHERE clause + + sqlWhere; // Here the latitude and longitude condition gets appended if provided + + List> result = jdbcHoardingsTemplate.queryForList(sqlQuery); + Map response = new HashMap<>(); + response.put("status", 200); + response.put("message", "Hoarding list by latlong"); + response.put("data", result); + + return Collections.singletonList(response); + } + + @Transactional + public List> getChallanPOSData( + MultiValueMap formData, + String orderid, + String loginid) { + + String sqlQuery = "SELECT al.`category_id`, al.`name`, al.`zone`, al.`ward`, " + + "CONCAT('https://gccservices.in/gccofficialapp/files', al.`image`) as imageurl, " + + "hi.`licenses_no`, hi.`fine_amount`, hi.`fine_status`, hi.`orderid`, " + + "CASE " + + "WHEN hi.`fine_to` = 1 THEN 'Ptax Owner' " + + "WHEN hi.`fine_to` = 2 THEN 'Agent' " + + "ELSE '' " + + "END AS fine_for_name, " + + "CASE " + + "WHEN hi.`fine_to` = 1 THEN COALESCE(hi.`ptax_name`, '') " + + "WHEN hi.`fine_to` = 2 THEN COALESCE(hi.`agency_name`, '') " + + "ELSE '' " + + "END AS fine_to_name, " + + "CASE " + + "WHEN hi.`fine_to` = 1 THEN COALESCE(hi.`ptax_mobile`, '') " + + "WHEN hi.`fine_to` = 2 THEN COALESCE(hi.`agency_mobile`, '') " + + "ELSE '' " + + "END AS fine_to_mobile, " + + "hit.`name` as status " + + "FROM `asset_list` as al " + + "INNER JOIN `hoardings_info` as hi ON hi.asset_id = al.id " + + "INNER JOIN `hoarding_info_type` as hit ON hit.id = hi.hitid " + + "WHERE al.`isactive` = 1 AND al.`isdelete` = 0 " + + "AND hi.`fine_status` <> 'Transaction success' " + + "AND hi.`fine_amount` > 0 "; + + if (orderid != null && !orderid.isEmpty() && !orderid.isBlank()) { + sqlQuery = sqlQuery + " AND hi.`orderid` = '" + orderid + "'"; + } + if (loginid != null && !loginid.isEmpty() && !loginid.isBlank()) { + sqlQuery = sqlQuery + " AND hi.`cby` = '" + loginid + "'"; + } + + // Debugging: Print the final SQL query for checking + System.out.println("Final SQL Query: " + sqlQuery); + + List> result = jdbcHoardingsTemplate.queryForList(sqlQuery); + Map response = new HashMap<>(); + response.put("status", 200); + response.put("message", "Challan Details"); + response.put("data", result); + + return Collections.singletonList(response); + } + + @Transactional + public List> updateSerialNumber( + MultiValueMap formData, + String tid, + String mid, + String serialNumber, + String orderid){ + String sqlQuery = "UPDATE hoardings_info SET tid = ?, mid = ?, serial_number = ? WHERE orderid = ? LIMIT 1"; + jdbcHoardingsTemplate.update(sqlQuery, tid, mid, serialNumber, orderid); + Map response = new HashMap<>(); + response.put("status", 200); + response.put("message", "Serial Number updated successfully"); + return Collections.singletonList(response); + } + + @Transactional + public List> storeBankTransaction(Map transactionData) { + + Map response = new HashMap<>(); + int lastInsertId = 0; + + // Extract data from the JSON object + String transactionResponseStatus = (String) transactionData.get("transactionResponseStatus"); + + // Check if the transaction was successful + if ("Transaction success".equalsIgnoreCase(transactionResponseStatus)) { + + String mid = (String) transactionData.get("mid"); + String tid = (String) transactionData.get("tid"); + String txnId = (String) transactionData.get("txnId"); + + // Fetch nested transaction response data + Map txnResponseData = (Map) transactionData.get("txnResponseData"); + + String bankName = (String) txnResponseData.get("bankName"); + String batchNumber = (String) txnResponseData.get("batchNumber"); + String transactionTitle = (String) txnResponseData.get("transactionTitle"); + String txnAID = (String) txnResponseData.get("txnAID"); + String txnApprCode = (String) txnResponseData.get("txnApprCode"); + String txnCardNo = (String) txnResponseData.get("txnCardNo"); + String txnCardType = (String) txnResponseData.get("txnCardType"); + String txnDate = (String) txnResponseData.get("txnDate"); + String txnInvoice = (String) txnResponseData.get("txnInvoice"); + String txnMode = (String) txnResponseData.get("txnMode"); + String txnRefNo = (String) txnResponseData.get("txnRefNo"); + String txnTC = (String) txnResponseData.get("txnTC"); + String txnTSI = (String) txnResponseData.get("txnTSI"); + String txnTVR = (String) txnResponseData.get("txnTVR"); + String txnTime = (String) txnResponseData.get("txnTime"); + + // Convert transaction amount properly + Double transactionAmount = Double.valueOf((String) txnResponseData.get("transactionAmount")); + + String sqlQuery = "INSERT INTO bank_transactions (mid, tid, txnId, bankName, batchNumber, transactionAmount, " + + "transactionTitle, txnAID, txnApprCode, txnCardNo, txnCardType, txnDate, txnInvoice, txnMode, txnRefNo, " + + "txnTC, txnTSI, txnTVR, txnTime) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; + + KeyHolder keyHolder = new GeneratedKeyHolder(); + + try { + int affectedRows = jdbcHoardingsTemplate.update(new PreparedStatementCreator() { + @Override + public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { + PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[]{"id"}); + ps.setString(1, mid); + ps.setString(2, tid); + ps.setString(3, txnId); + ps.setString(4, bankName); + ps.setString(5, batchNumber); + ps.setDouble(6, transactionAmount); + ps.setString(7, transactionTitle); + ps.setString(8, txnAID); + ps.setString(9, txnApprCode); + ps.setString(10, txnCardNo); + ps.setString(11, txnCardType); + ps.setString(12, txnDate); + ps.setString(13, txnInvoice); + ps.setString(14, txnMode); + ps.setString(15, txnRefNo); + ps.setString(16, txnTC); + ps.setString(17, txnTSI); + ps.setString(18, txnTVR); + ps.setString(19, txnTime); + return ps; + } + }, keyHolder); + + if (affectedRows > 0) { + Number generatedId = keyHolder.getKey(); + lastInsertId = (generatedId != null) ? generatedId.intValue() : 0; + + updatePaymentStatus(txnId, transactionResponseStatus); + + // Fetch inserted data for response, joining `penalty_challan` and `bank_transactions` + String sqlQuery_joined = "SELECT al.`category_id`, al.`name`, al.`zone`, al.`ward`, " + + "CONCAT('https://gccservices.in/gccofficialapp/files', al.`image`) as imageurl, " + + "hi.`licenses_no`, hi.`fine_amount`, hi.`fine_status`, hi.`orderid`, " + + "CASE " + + "WHEN hi.`fine_to` = 1 THEN 'Ptax Owner' " + + "WHEN hi.`fine_to` = 2 THEN 'Agent' " + + "ELSE '' " + + "END AS fine_for_name, " + + "CASE " + + "WHEN hi.`fine_to` = 1 THEN COALESCE(hi.`ptax_name`, '') " + + "WHEN hi.`fine_to` = 2 THEN COALESCE(hi.`agency_name`, '') " + + "ELSE '' " + + "END AS fine_to_name, " + + "CASE " + + "WHEN hi.`fine_to` = 1 THEN COALESCE(hi.`ptax_mobile`, '') " + + "WHEN hi.`fine_to` = 2 THEN COALESCE(hi.`agency_mobile`, '') " + + "ELSE '' " + + "END AS fine_to_mobile, " + + "hit.`name` as status " + + "FROM `asset_list` as al " + + "INNER JOIN `hoardings_info` as hi ON hi.asset_id = al.id " + + "INNER JOIN `hoarding_info_type` as hit ON hit.id = hi.hitid " + + "WHERE al.`isactive` = 1 AND al.`isdelete` = 0 " + + "AND hi.`orderid` = ?"; + + System.out.println(sqlQuery_joined); + + // Execute the query + List> result = jdbcHoardingsTemplate.queryForList(sqlQuery_joined, txnId); + + response.put("status", 200); + response.put("message", "Transaction stored successfully!"); + response.put("data", result); + + } else { + response.put("status", 201); + response.put("message", "Failed to store the transaction."); + response.put("data", ""); + } + } catch (DataAccessException e) { + response.put("status", 500); + response.put("message", "Database error while storing transaction."); + response.put("error", e.getMessage()); + e.printStackTrace(); // This will give you more detail in logs + } + } else { + response.put("status", 400); + response.put("message", "Transaction failed or invalid status."); + } + + return Collections.singletonList(response); + } + + @Transactional + public List> storeFailedBankTransaction(Map transactionData) { + + Map response = new HashMap<>(); + int lastInsertId = 0; + + // Extract data from the JSON object + String transactionResponseStatus = (String) transactionData.get("transactionResponseStatus"); + + // Check if the transaction was successful + if ("Transaction cancelled".equalsIgnoreCase(transactionResponseStatus)) { + + String mid = (String) transactionData.get("mid"); + String tid = (String) transactionData.get("tid"); + String txnId = (String) transactionData.get("txnId"); + + // Fetch nested transaction response data + Map txnResponseData = (Map) transactionData.get("txnResponseData"); + + String bankName = (String) txnResponseData.get("bankName"); + String batchNumber = (String) txnResponseData.get("batchNumber"); + String transactionTitle = (String) txnResponseData.get("transactionTitle"); + String txnAID = (String) txnResponseData.get("txnAID"); + String txnApprCode = (String) txnResponseData.get("txnApprCode"); + String txnCardNo = (String) txnResponseData.get("txnCardNo"); + String txnCardType = (String) txnResponseData.get("txnCardType"); + String txnDate = (String) txnResponseData.get("txnDate"); + String txnInvoice = (String) txnResponseData.get("txnInvoice"); + String txnMode = (String) txnResponseData.get("txnMode"); + String txnRefNo = (String) txnResponseData.get("txnRefNo"); + String txnTC = (String) txnResponseData.get("txnTC"); + String txnTSI = (String) txnResponseData.get("txnTSI"); + String txnTVR = (String) txnResponseData.get("txnTVR"); + String txnTime = (String) txnResponseData.get("txnTime"); + + // Convert transaction amount properly + //Double transactionAmount = Double.valueOf((String) txnResponseData.get("transactionAmount")); + + // Get the transactionAmount from txnResponseData + String transactionAmountStr = (String) txnResponseData.get("transactionAmount"); + + // Check if the transactionAmount is not null and not empty before converting + Double transactionAmountTemp = null; + + if (transactionAmountStr != null && !transactionAmountStr.trim().isEmpty()) { + try { + // Convert the valid string to a Double + transactionAmountTemp = Double.valueOf(transactionAmountStr); + } catch (NumberFormatException e) { + // Handle the case where the string cannot be parsed to a Double // Log the error or throw a custom exception + System.out.println("Error: Unable to parse transactionAmount to Double. " + e.getMessage()); + transactionAmountTemp = 0.0; // Set to a default value or handle as needed + } + } else { + // Handle the case where transactionAmount is empty or null + transactionAmountTemp = 0.0; // Default value or handle as needed + } + + Double transactionAmount = transactionAmountTemp; + + String sqlQuery = "INSERT INTO bank_failed_transactions (mid, tid, txnId, bankName, batchNumber, transactionAmount, " + + "transactionTitle, txnAID, txnApprCode, txnCardNo, txnCardType, txnDate, txnInvoice, txnMode, txnRefNo, " + + "txnTC, txnTSI, txnTVR, txnTime) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; + + KeyHolder keyHolder = new GeneratedKeyHolder(); + + try { + int affectedRows = jdbcHoardingsTemplate.update(new PreparedStatementCreator() { + @Override + public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { + PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[]{"id"}); + ps.setString(1, mid); + ps.setString(2, tid); + ps.setString(3, txnId); + ps.setString(4, bankName); + ps.setString(5, batchNumber); + ps.setDouble(6, transactionAmount); + ps.setString(7, transactionTitle); + ps.setString(8, txnAID); + ps.setString(9, txnApprCode); + ps.setString(10, txnCardNo); + ps.setString(11, txnCardType); + ps.setString(12, txnDate); + ps.setString(13, txnInvoice); + ps.setString(14, txnMode); + ps.setString(15, txnRefNo); + ps.setString(16, txnTC); + ps.setString(17, txnTSI); + ps.setString(18, txnTVR); + ps.setString(19, txnTime); + return ps; + } + }, keyHolder); + + if (affectedRows > 0) { + Number generatedId = keyHolder.getKey(); + lastInsertId = (generatedId != null) ? generatedId.intValue() : 0; + + updatePaymentStatus(txnId, transactionResponseStatus); + + // Fetch inserted data for response, joining `penalty_challan` and `bank_transactions` + // Fetch inserted data for response, joining `penalty_challan` and `bank_transactions` + String sqlQuery_joined = "SELECT al.`category_id`, al.`name`, al.`zone`, al.`ward`, " + + "CONCAT('https://gccservices.in/gccofficialapp/files', al.`image`) as imageurl, " + + "hi.`licenses_no`, hi.`fine_amount`, hi.`fine_status`, hi.`orderid`, " + + "CASE " + + "WHEN hi.`fine_to` = 1 THEN 'Ptax Owner' " + + "WHEN hi.`fine_to` = 2 THEN 'Agent' " + + "ELSE '' " + + "END AS fine_for_name, " + + "CASE " + + "WHEN hi.`fine_to` = 1 THEN COALESCE(hi.`ptax_name`, '') " + + "WHEN hi.`fine_to` = 2 THEN COALESCE(hi.`agency_name`, '') " + + "ELSE '' " + + "END AS fine_to_name, " + + "CASE " + + "WHEN hi.`fine_to` = 1 THEN COALESCE(hi.`ptax_mobile`, '') " + + "WHEN hi.`fine_to` = 2 THEN COALESCE(hi.`agency_mobile`, '') " + + "ELSE '' " + + "END AS fine_to_mobile, " + + "hit.`name` as status " + + "FROM `asset_list` as al " + + "INNER JOIN `hoardings_info` as hi ON hi.asset_id = al.id " + + "INNER JOIN `hoarding_info_type` as hit ON hit.id = hi.hitid " + + "WHERE al.`isactive` = 1 AND al.`isdelete` = 0 " + + "AND hi.`orderid` = ?"; + System.out.println(sqlQuery_joined); + // Execute the query + List> result = jdbcHoardingsTemplate.queryForList(sqlQuery_joined, txnId); + + response.put("status", 200); + response.put("message", "Transaction stored successfully!"); + response.put("data", result); + } else { + response.put("status", 201); + response.put("message", "Failed to store the transaction."); + response.put("data", ""); + } + } catch (DataAccessException e) { + response.put("status", 500); + response.put("message", "Database error while storing transaction."); + response.put("error", e.getMessage()); + e.printStackTrace(); // This will give you more detail in logs + } + } else { + response.put("status", 400); + response.put("message", "Transaction failed or invalid status."); + } + + return Collections.singletonList(response); + } + + public String updatePaymentStatus(String orderid, String status) { + String sqlQuery = "UPDATE `hoardings_info` SET `fine_status` = ? WHERE orderid = ? LIMIT 1"; + jdbcHoardingsTemplate.update(sqlQuery, status, orderid); + return "success"; + } + + public List> insertHoardingUpdatedData( + MultiValueMap formData, + String asset_id, + String update_type, + String removed_type, + MultipartFile file, + String licenses_no_visible, + String validity_date_visible, + String not_as_per_size, + String licenses_no, + String cby) { + + String update_image = fileUpload("hoarding_asset",asset_id,"asset_update",file); + + String sqlQuery = "INSERT INTO `hoarding_update`" + + "(`asset_id`, `update_type`, `removed_type`, `update_image`, `licenses_no_visible`, `validity_date_visible`, " + + "`not_as_per_size`, `licenses_no`,`cby`) " + + "VALUES (?,?,?,?,?,?,?,?,?)"; + + Map response = new HashMap<>(); + int lastInsertId = 0; + String status="error"; + KeyHolder keyHolder = new GeneratedKeyHolder(); + + //setHoadingInfoinactive(asset_id); // Update isactive as 0 for old records + + try { + int affectedRows = jdbcHoardingsTemplate.update(new PreparedStatementCreator() { + @Override + public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { + PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[]{"id"}); + ps.setString(1, asset_id); + ps.setString(2, update_type); + ps.setString(3, removed_type); + ps.setString(4, update_image); + ps.setString(5, licenses_no_visible); + ps.setString(6, validity_date_visible); + ps.setString(7, not_as_per_size); + ps.setString(8, licenses_no); + ps.setString(9, cby); + return ps; + } + }, keyHolder); + + if (affectedRows > 0) { + Number generatedId = keyHolder.getKey(); + lastInsertId = (generatedId != null) ? generatedId.intValue() : 0; + response.put("insertId", lastInsertId); + response.put("status", "success"); + response.put("message", "Hoardings Info updated successfully!"); + System.out.println("Hoardings Info updated successfully! Insert ID: " + generatedId); + //System.out.println("update_type :"+update_type); + + if ("Authorized".equals(update_type)) { + updateHoardingStatus(asset_id, "1"); // Update current status + updateHoardingLicense(asset_id, licenses_no); // Update new licenses number + } else if ("Un-Authorized".equals(update_type)) { + updateHoardingStatus(asset_id, "3"); // Update current status + } else if ("Removed by Own".equals(update_type)) { + updateHoardingStatus(asset_id, "4"); // Update current status + } + + } else { + response.put("status", "error"); + response.put("message", "Failed to update the hoardings Info (Update)."); + } + } catch (DataAccessException e) { + System.out.println("Data Access Exception:"); + Throwable rootCause = e.getMostSpecificCause(); + if (rootCause instanceof SQLException) { + SQLException sqlException = (SQLException) rootCause; + System.out.println("SQL State: " + sqlException.getSQLState()); + System.out.println("Error Code: " + sqlException.getErrorCode()); + System.out.println("Message: " + sqlException.getMessage()); + response.put("status", "error"); + response.put("message", sqlException.getMessage()); + response.put("sqlState", sqlException.getSQLState()); + response.put("errorCode", sqlException.getErrorCode()); + } else { + System.out.println("Message: " + rootCause.getMessage()); + response.put("status", "error"); + response.put("message", rootCause.getMessage()); + } + } + + return Collections.singletonList(response); + } + + public String setHoadingInfoinactive(String asset_id) { + String sqlQuery = "UPDATE `hoarding_update` SET `isactive` = 0 WHERE `asset_id` = ?"; + jdbcHoardingsTemplate.update(sqlQuery, asset_id); + return "success"; + } + + public String updateHoardingStatus(String asset_id, String status) { + //System.out.println("update_type :"+ status + " & ID :"+asset_id); + String sqlQuery = "UPDATE `hoardings_info` SET `hitid` = ? WHERE `asset_id` = ? LIMIT 1"; + jdbcHoardingsTemplate.update(sqlQuery, status, asset_id); + + // Generate Challan and store (Update in info table) if hitid==3 (UnAuterized) + if("3".equals(status)) { + int assetIdInt = Integer.parseInt(asset_id); // Convert the String asset_id to an int + createChallanbyAssetId(assetIdInt, "Challan created", status); + } + + return "success"; + } + + public String updateHoardingLicense(String asset_id, String licenses_no) { + //System.out.println("update_type :"+ status + " & ID :"+asset_id); + String sqlQuery = "UPDATE `hoardings_info` SET `licenses_no` = ? WHERE `asset_id` = ? LIMIT 1"; + jdbcHoardingsTemplate.update(sqlQuery, licenses_no, asset_id); + return "success"; + } + + public String getWardByLoginId(String loginid, String type) { + String sqlQuery = "SELECT `ward` FROM `hoading_user_list` WHERE `userid` = ? AND `type` = ? LIMIT 1"; + + // Query the database using queryForList + List> results = jdbcHoardingsTemplate.queryForList(sqlQuery, loginid, type); + + // Check if results is not empty and extract the ward value + if (!results.isEmpty()) { + // Extract the ward value from the first result + return (String) results.get(0).get("ward"); + } + + // Handle the case where no result is found + return "000"; // or return null based on your needs + } + + @Transactional + public List> unAuterrizedAssetlist( + MultiValueMap formData, + String loginid + ) { + + String ward = getWardByLoginId(loginid,"ae"); + + String sqlQuery = "SELECT al.`id`, al.`category_id`, ac.`name` AS category_name, al.`name`, al.`image`, al.`latitude`, " + + "al.`longitude`, al.`zone`, al.`ward`, al.`streetid`, al.`streetname`, al.`cdate`, al.`cby`, al.`remarks`, " + + "hi.`hitid`, hi.`licenses_info`, hi.`licenses_no`, hi.`validity_date`, hi.`case_no`, " + + "hi.`ptax_no`, hi.`ptax_name`, hi.`ptax_mobile`, hi.`agency_name`, hi.`agency_mobile`, hi.`fine_to`, " + + "hi.`fine_amount`, hi.`fine_status`, hi.`orderid`, hi.`cdate` as ae_cdate, hi.`cby` as ae_cby, " + + "hi.`tid`, hi.`mid`, hi.`serial_number`, " + + "hit.`name` AS hoarding_info_type, " + + "CONCAT('"+fileBaseUrl+"/gccofficialapp/files', al.`image`) AS imageurl " + + "FROM `asset_list` al " + + "INNER JOIN `hoardings_info` hi ON al.id = hi.asset_id " + + "INNER JOIN `asset_category` ac ON ac.id = al.category_id " + + "INNER JOIN `hoarding_info_type` hit ON hit.id = hi.hitid " + + "WHERE al.`isactive` = 1 AND al.`isdelete` = 0 AND hi.hitid = 3 " + + "AND hi.cdate < (NOW() - INTERVAL 24 HOUR) AND al.ward = ?"; // This filters records within the last 24 hours + + List> result = jdbcHoardingsTemplate.queryForList(sqlQuery, ward); + Map response = new HashMap<>(); + response.put("status", 200); + response.put("message", "Un-Auterrize Hoarding list By Login"); + response.put("data", result); + + return Collections.singletonList(response); + } + + @Transactional + public List> unauterrizedassetlistbylatlong( + MultiValueMap formData, + String latitude, + String longitude, + String assetid, + String loginid) { + + String sqlWhere = ""; + + if (latitude != null && longitude != null && !latitude.isBlank() && !latitude.isEmpty() && !longitude.isBlank() + && !longitude.isEmpty()) { + sqlWhere += " AND ((6371008.8 * acos(ROUND(cos(radians(" + latitude + + ")) * cos(radians(al.latitude)) * cos(radians(al.longitude) - radians(" + longitude + + ")) + sin(radians(" + latitude + ")) * sin(radians(al.latitude)), 9))) < 500)"; + } + + String sqlQuery = "SELECT al.`id`, al.`category_id`, ac.`name` AS category_name, al.`name`, al.`image`, al.`latitude`, " + + "al.`longitude`, al.`zone`, al.`ward`, al.`streetid`, al.`streetname`, al.`cdate`, al.`cby`, al.`remarks`, " + + "hi.`hitid`, hi.`licenses_info`, hi.`licenses_no`, hi.`validity_date`, hi.`case_no`, " + + "hi.`ptax_no`, hi.`ptax_name`, hi.`ptax_mobile`, hi.`agency_name`, hi.`agency_mobile`, hi.`fine_to`, " + + "hi.`fine_amount`, hi.`fine_status`, hi.`orderid`, hi.`cdate` as ae_cdate, hi.`cby` as ae_cby, " + + "hi.`tid`, hi.`mid`, hi.`serial_number`, " + + "hit.`name` AS hoarding_info_type, " + + "CONCAT('"+fileBaseUrl+"/gccofficialapp/files', al.`image`) AS imageurl " + + "FROM `asset_list` al " + + "INNER JOIN `hoardings_info` hi ON al.id = hi.asset_id " + + "INNER JOIN `asset_category` ac ON ac.id = al.category_id " + + "INNER JOIN `hoarding_info_type` hit ON hit.id = hi.hitid " + + "WHERE al.`isactive` = 1 AND al.`isdelete` = 0 AND al.id = ? " // This is the starting part of WHERE clause + + sqlWhere; // Here the latitude and longitude condition gets appended if provided + + List> result = jdbcHoardingsTemplate.queryForList(sqlQuery,assetid); + Map response = new HashMap<>(); + response.put("status", 200); + response.put("message", "Un-Auterrize Hoarding list by latlong"); + response.put("data", result); + + return Collections.singletonList(response); + } + + public List> insertHoardingUpdatedDataAE( + MultiValueMap formData, + String asset_id, + String remarks, + String removed_type, + MultipartFile file, + //MultipartFile firfile, + //String fir, + //String fir_number, + //String material_collected, + //MultipartFile materialfile, + String loginId) { + + // Initialize the variables as final so they can be used in the anonymous class + final String update_image = (file != null && !file.isEmpty()) ? fileUpload("hoarding_asset", asset_id, "asset_ae_update", file) : ""; + //final String materail_receipt = (materialfile != null && !materialfile.isEmpty()) ? fileUpload("hoarding_asset", asset_id, "asset_ae_materail_update", materialfile) : ""; + //final String firfilepath = (firfile != null && !firfile.isEmpty()) ? fileUpload("hoarding_asset", asset_id, "asset_ae_fir_update", firfile) : ""; + + String sqlQuery = "INSERT INTO `hoarding_ae_update`( `asset_id`, `update_image`, `remarks`, `removed_type`, " + + "`fir`, `fir_number`, `fir_image`, `material_collected`, `material_receipt`, `cby`,`fir_remarks`,`material_remarks`) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"; + + Map response = new HashMap<>(); + int lastInsertId = 0; + String status = "error"; + KeyHolder keyHolder = new GeneratedKeyHolder(); + + setHoadingAEUpdateinactive(asset_id); + + // Dummy + String fir=""; + String fir_number=""; + String firfilepath=""; + String fir_remarks=""; + String material_collected=""; + String materail_receipt=""; + String material_remarks=""; + + try { + int affectedRows = jdbcHoardingsTemplate.update(new PreparedStatementCreator() { + @Override + public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { + PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[]{"id"}); + ps.setString(1, asset_id); + ps.setString(2, update_image); // Can be null if no file was uploaded + ps.setString(3, remarks); + ps.setString(4, removed_type); + ps.setString(5, fir); + ps.setString(6, fir_number); + ps.setString(7, firfilepath); // Can be null if no FIR file was uploaded + ps.setString(8, material_collected); + ps.setString(9, materail_receipt); // Can be null if no Material file was uploaded + ps.setString(10, loginId); + ps.setString(11, fir_remarks); + ps.setString(12, material_remarks); + return ps; + } + }, keyHolder); + + if (affectedRows > 0) { + Number generatedId = keyHolder.getKey(); + lastInsertId = (generatedId != null) ? generatedId.intValue() : 0; + response.put("insertId", lastInsertId); + response.put("status", "success"); + response.put("message", "AE Hoardings Info updated successfully!"); + System.out.println("AE Hoardings Info updated successfully! Insert ID: " + generatedId); + + // Update hoarding Status based on removed Type + if ("GCC".equals(removed_type)) { + updateHoardingStatus(asset_id, "4"); // Update current status + + // Weight + if("".equals(material_collected) || "".equals(materail_receipt)) { + updateHoadingAEmaterialPendingStatus(lastInsertId,1); + } + else { + updateHoadingAEmaterialPendingStatus(lastInsertId,0); + } + + } else if ("Violator".equals(removed_type)) { + updateHoardingStatus(asset_id, "4"); // Update current status + updateHoadingAEmaterialPendingStatus(lastInsertId,0); + } + + // FIR + if("".equals(fir_number) || "".equals(firfilepath)) { + updateHoadingAEFIRPendingStatus(lastInsertId,1); + } + else { + updateHoadingAEFIRPendingStatus(lastInsertId,0); + } + + } else { + response.put("status", "error"); + response.put("message", "Failed to update the AE hoardings Info (Update)."); + } + } catch (DataAccessException e) { + System.out.println("Data Access Exception:"); + Throwable rootCause = e.getMostSpecificCause(); + if (rootCause instanceof SQLException) { + SQLException sqlException = (SQLException) rootCause; + System.out.println("SQL State: " + sqlException.getSQLState()); + System.out.println("Error Code: " + sqlException.getErrorCode()); + System.out.println("Message: " + sqlException.getMessage()); + response.put("status", "error"); + response.put("message", sqlException.getMessage()); + response.put("sqlState", sqlException.getSQLState()); + response.put("errorCode", sqlException.getErrorCode()); + } else { + System.out.println("Message: " + rootCause.getMessage()); + response.put("status", "error"); + response.put("message", rootCause.getMessage()); + } + } + + return Collections.singletonList(response); + } + + public List> updateMaterialInfo( + String id, + String asset_id, + String material_collected, + String material_remarks, + MultipartFile materialfile) { + + final String materail_receipt = (materialfile != null && !materialfile.isEmpty()) ? fileUpload("hoarding_asset", asset_id, "asset_ae_materail_update", materialfile) : ""; + + Map response = new HashMap<>(); + + String sqlQuery = "UPDATE `hoarding_ae_update` SET `material_collected`=?, `material_receipt`=?, `material_remarks`=? WHERE `id` = ?"; + jdbcHoardingsTemplate.update(sqlQuery, material_collected, materail_receipt, material_remarks, id); + + response.put("status", "success"); + response.put("message", "AE Hoardings Material Info updated successfully!"); + + int idInt = Integer.parseInt(id); // Convert String to int + + updateHoadingAEmaterialPendingStatus(idInt,0); + + return Collections.singletonList(response); + } + + public List> updateFirInfo( + String id, + String asset_id, + String fir_number, + String fir_remarks, + MultipartFile firfile) { + + final String firfilepath = (firfile != null && !firfile.isEmpty()) ? fileUpload("hoarding_asset", asset_id, "asset_ae_fir_update", firfile) : ""; + + Map response = new HashMap<>(); + + String sqlQuery = "UPDATE `hoarding_ae_update` SET `fir_number`=?, `fir_image`=?, `fir_remarks`=? WHERE `asset_id` = ?"; + jdbcHoardingsTemplate.update(sqlQuery, fir_number, firfilepath, fir_remarks, asset_id); + + response.put("status", "success"); + response.put("message", "AE Hoardings FIR Info updated successfully!"); + + int idInt = Integer.parseInt(id); // Convert String to int + + updateHoadingAEFIRPendingStatus(idInt,0); + + return Collections.singletonList(response); + } + + public String setHoadingAEUpdateinactive(String asset_id) { + String sqlQuery = "UPDATE `hoarding_ae_update` SET `isactive` = 0 WHERE `asset_id` = ?"; + jdbcHoardingsTemplate.update(sqlQuery, asset_id); + return "success"; + } + + public String updateHoadingAEmaterialPendingStatus(int id,int status) { + String sqlQuery = "UPDATE `hoarding_ae_update` SET `material_pending` = ? WHERE `id` = ?"; + jdbcHoardingsTemplate.update(sqlQuery, status, id); + return "success"; + } + + public String updateHoadingAEFIRPendingStatus(int id,int status) { + String sqlQuery = "UPDATE `hoarding_ae_update` SET `fir_pending` = ? WHERE `id` = ?"; + jdbcHoardingsTemplate.update(sqlQuery, status, id); + return "success"; + } + + @Transactional + public List> unAuterrizedAssetlistAEPending( + MultiValueMap formData, + String pendingType, + String loginid) { + + String sqlQuery = "SELECT " + + " al.`id`, " + + " al.`category_id`, " + + " ac.`name` AS category_name, " + + " al.`name`, " + + " al.`image`, " + + " al.`latitude`, " + + " al.`longitude`, " + + " al.`zone`, " + + " al.`ward`, " + + " al.`streetid`, " + + " al.`streetname`, " + + " al.`cdate`, " + + " al.`cby`, " + + " al.`remarks`, " + + " hi.`hitid`, " + + " hi.`licenses_info`, " + + " hi.`licenses_no`, " + + " hi.`validity_date`, " + + " hi.`case_no`, " + + " hi.`ptax_no`, " + + " hi.`ptax_name`, " + + " hi.`ptax_mobile`, " + + " hi.`agency_name`, " + + " hi.`agency_mobile`, " + + " hi.`fine_to`, " + + " hi.`fine_amount`, hi.`fine_status`, hi.`orderid`, hi.`cdate` as ae_cdate, hi.`cby` as ae_cby, " + + " hi.`tid`, hi.`mid`, hi.`serial_number`, " + + " hit.`name` AS hoarding_info_type, " + + " CONCAT('https://gccservices.in/gccofficialapp/files', al.`image`) AS imageurl, " + + " haeu.`update_image`, " + + " haeu.`remarks`, " + + " haeu.`removed_type`, " + + " haeu.`fir`, " + + " haeu.`fir_number`, " + + " haeu.`fir_image`, " + + " haeu.`material_collected`, " + + " haeu.`material_receipt`, " + + " haeu.`cdate` AS ae_cdate, " + + " haeu.`cby` AS ae_cby, " + + " haeu.`material_pending`, " + + " haeu.`fir_pending`, " + + " haeu.`id` AS ae_data_id, " + + " CONCAT('https://gccservices.in/gccofficialapp/files', haeu.`update_image`) AS ae_update_imageurl, " + + " CONCAT('https://gccservices.in/gccofficialapp/files', haeu.`material_receipt`) AS ae_material_imageurl, " + + " CONCAT('https://gccservices.in/gccofficialapp/files', haeu.`fir_image`) AS ae_fir_imageurl " + + "FROM " + + " `asset_list` al " + + "INNER JOIN " + + " `hoardings_info` hi ON al.id = hi.asset_id " + + "INNER JOIN " + + " `asset_category` ac ON ac.id = al.category_id " + + "INNER JOIN " + + " `hoarding_info_type` hit ON hit.id = hi.hitid " + + "INNER JOIN " + + " `hoarding_ae_update` haeu ON haeu.asset_id = hi.asset_id " + + "WHERE " + + " (al.`isactive` = 1 AND al.`isdelete` = 0) "; + + String sqlQuery_where=" AND 1=0 AND haeu.`cby`= ?"; + + if("materail".equals(pendingType)) { + sqlQuery_where = "AND (haeu.material_pending = 1) AND (haeu.`cby` = ? AND haeu.isactive=1) AND haeu.`removed_type`='GCC'"; + } + + if("fir".equals(pendingType)) { + sqlQuery_where = "AND (haeu.`fir_pending` = 1) AND (haeu.`cby` = ? AND haeu.isactive=1)"; + } + + sqlQuery = sqlQuery + sqlQuery_where; + + List> result = jdbcHoardingsTemplate.queryForList(sqlQuery,loginid); + Map response = new HashMap<>(); + response.put("status", 200); + response.put("message", "Un-Auterrize AE Pending Hoarding list By Login"); + response.put("data", result); + + return Collections.singletonList(response); + } + + @Transactional + public List> ReportTile( + String fromDate, + String toDate) { + + String sqlQuery = "SELECT " + + " hit.`name` AS hoarding_info_type, " + + " COUNT(DISTINCT al.id) AS total_count, " + + " SUM(CASE WHEN hi.`fine_status` = 'Transaction success' THEN hi.`fine_amount` ELSE 0 END) AS total_fine_amount, " + + " SUM(SUM(CASE WHEN hi.`fine_status` = 'Transaction success' THEN hi.`fine_amount` ELSE 0 END)) OVER() AS total_amount " + + "FROM " + + " `asset_list` al " + + "LEFT JOIN " + + " `hoardings_info` hi ON al.id = hi.asset_id " + + "LEFT JOIN " + + " `asset_category` ac ON ac.id = al.category_id " + + "LEFT JOIN " + + " `hoarding_info_type` hit ON hit.id = hi.hitid " + + "WHERE " + + " al.`isactive` = 1 " + + " AND al.`isdelete` = 0 " + + " AND DATE(al.`cdate`) BETWEEN STR_TO_DATE(?, '%d-%m-%Y') AND STR_TO_DATE(?, '%d-%m-%Y') " + + " AND hit.`name` IS NOT NULL " + + "GROUP BY " + + " hit.`name` " + + "ORDER BY " + + " hit.`id`"; + + List> result = jdbcHoardingsTemplate.queryForList(sqlQuery, fromDate, toDate); + Map response = new HashMap<>(); + response.put("status", 200); + response.put("message", "Main Report Data"); + response.put("data", result); + + return Collections.singletonList(response); + } + + @Transactional + public List> reportZoneList( + String fromDate, + String toDate) { + + String sqlQuery = "SELECT " + + " al.`zone`, " + + " COUNT(DISTINCT CASE WHEN hit.`name` = 'Authorized' THEN al.id END) AS Authorized, " + + " COUNT(DISTINCT CASE WHEN hit.`name` = 'Court Case' THEN al.id END) AS Court_Case, " + + " COUNT(DISTINCT CASE WHEN hit.`name` = 'Unauthorized' THEN al.id END) AS Unauthorized, " + + " COUNT(DISTINCT CASE WHEN hit.`name` = 'Removed' THEN al.id END) AS Removed, " + + " SUM(CASE WHEN hit.`name` = 'Authorized' AND hi.`fine_status` = 'Transaction success' THEN hi.`fine_amount` ELSE 0 END) AS Authorized_Amount, " + + " SUM(CASE WHEN hit.`name` = 'Court Case' AND hi.`fine_status` = 'Transaction success' THEN hi.`fine_amount` ELSE 0 END) AS Court_Case_Amount, " + + " SUM(CASE WHEN hit.`name` = 'Unauthorized' AND hi.`fine_status` = 'Transaction success' THEN hi.`fine_amount` ELSE 0 END) AS Unauthorized_Amount, " + + " SUM(CASE WHEN hit.`name` = 'Removed' AND hi.`fine_status` = 'Transaction success' THEN hi.`fine_amount` ELSE 0 END) AS Removed_Amount, " + + " SUM(CASE WHEN hi.`fine_status` = 'Transaction success' THEN hi.`fine_amount` ELSE 0 END) AS Total_Amount " + + "FROM " + + " `asset_list` al " + + "LEFT JOIN " + + " `hoardings_info` hi ON al.id = hi.asset_id " + + "LEFT JOIN " + + " `asset_category` ac ON ac.id = al.category_id " + + "LEFT JOIN " + + " `hoarding_info_type` hit ON hit.id = hi.hitid " + + "WHERE " + + " al.`isactive` = 1 " + + " AND al.`isdelete` = 0 " + + " AND DATE(al.`cdate`) BETWEEN STR_TO_DATE(?, '%d-%m-%Y') AND STR_TO_DATE(?, '%d-%m-%Y') " + + " AND hit.`name` IS NOT NULL " + + "GROUP BY " + + " al.`zone` " + + "ORDER BY " + + " al.`zone` "; + + List> result = jdbcHoardingsTemplate.queryForList(sqlQuery, fromDate, toDate); + Map response = new HashMap<>(); + response.put("status", 200); + response.put("message", "Main Report Data"); + response.put("data", result); + + return Collections.singletonList(response); + } + + @Transactional + public List> reportWardList( + String zone, + String fromDate, + String toDate) { + + String sqlQuery = "SELECT " + + " al.`ward`," + + " COUNT(DISTINCT CASE WHEN hit.`name` = 'Authorized' THEN al.id END) AS Authorized, " + + " COUNT(DISTINCT CASE WHEN hit.`name` = 'Court Case' THEN al.id END) AS Court_Case, " + + " COUNT(DISTINCT CASE WHEN hit.`name` = 'Unauthorized' THEN al.id END) AS Unauthorized, " + + " COUNT(DISTINCT CASE WHEN hit.`name` = 'Removed' THEN al.id END) AS Removed, " + + " SUM(CASE WHEN hit.`name` = 'Authorized' AND hi.`fine_status` = 'Transaction success' THEN hi.`fine_amount` ELSE 0 END) AS Authorized_Amount, " + + " SUM(CASE WHEN hit.`name` = 'Court Case' AND hi.`fine_status` = 'Transaction success' THEN hi.`fine_amount` ELSE 0 END) AS Court_Case_Amount, " + + " SUM(CASE WHEN hit.`name` = 'Unauthorized' AND hi.`fine_status` = 'Transaction success' THEN hi.`fine_amount` ELSE 0 END) AS Unauthorized_Amount, " + + " SUM(CASE WHEN hit.`name` = 'Removed' AND hi.`fine_status` = 'Transaction success' THEN hi.`fine_amount` ELSE 0 END) AS Removed_Amount, " + + " SUM(CASE WHEN hi.`fine_status` = 'Transaction success' THEN hi.`fine_amount` ELSE 0 END) AS Total_Amount " + + "FROM " + + " `asset_list` al " + + "LEFT JOIN " + + " `hoardings_info` hi ON al.id = hi.asset_id " + + "LEFT JOIN " + + " `asset_category` ac ON ac.id = al.category_id " + + "LEFT JOIN " + + " `hoarding_info_type` hit ON hit.id = hi.hitid " + + "WHERE " + + " al.`isactive` = 1 " + + " AND al.`isdelete` = 0 " + + " AND al.`zone` = ? " + + " AND DATE(al.`cdate`) BETWEEN STR_TO_DATE(?, '%d-%m-%Y') AND STR_TO_DATE(?, '%d-%m-%Y') " + + " AND hit.`name` IS NOT NULL " + + "GROUP BY " + + " al.`ward` " + + "ORDER BY " + + " al.`ward`"; + + List> result = jdbcHoardingsTemplate.queryForList(sqlQuery, zone, fromDate, toDate); + Map response = new HashMap<>(); + response.put("status", 200); + response.put("message", "Main Report Data"); + response.put("data", result); + + return Collections.singletonList(response); + } + + @Transactional + public List> reportListBySelect( + String ward, + String hitid, + String fromDate, + String toDate) { + + String sqlQuery = "SELECT " + + " al.`id`, " + + " al.`category_id`, " + + " ac.`name` AS category_name, " + + " al.`name`, " + + " al.`image`, " + + " al.`latitude`, " + + " al.`longitude`, " + + " al.`zone`, " + + " al.`ward`, " + + " al.`streetid`, " + + " al.`streetname`, " + + " al.`cdate`, " + + " al.`cby`, " + + " al.`remarks`, " + + " hi.`hitid`, " + + " hi.`licenses_info`, " + + " hi.`licenses_no`, " + + " hi.`validity_date`, " + + " hi.`case_no`, " + + " hi.`ptax_no`, " + + " hi.`ptax_name`, " + + " hi.`ptax_mobile`, " + + " hi.`agency_name`, " + + " hi.`agency_mobile`, " + + " hi.`fine_to`, " + + " hi.`fine_amount`, " + + " hi.`fine_status`, " + + " hi.`orderid`, " + + " hi.`cdate` as ae_cdate, " + + " hi.`cby` as ae_cby, " + + " hi.`tid`, " + + " hi.`mid`, " + + " hi.`serial_number`, " + + " hit.`name` AS hoarding_info_type, " + + " CONCAT('https://gccservices.in/gccofficialapp/files', al.`image`) AS imageurl, " + + " haeu.`update_image`, " + + " haeu.`remarks`, " + + " haeu.`removed_type`, " + + " haeu.`fir`, " + + " haeu.`fir_number`, " + + " haeu.`fir_image`, " + + " haeu.`material_collected`, " + + " haeu.`material_receipt`, " + + " haeu.`cdate` AS ae_cdate, " + + " haeu.`cby` AS ae_cby, " + + " haeu.`material_pending`, " + + " haeu.`fir_pending`, " + + " haeu.`id` AS ae_data_id, " + + " CONCAT('https://gccservices.in/gccofficialapp/files', haeu.`update_image`) AS ae_update_imageurl, " + + " CONCAT('https://gccservices.in/gccofficialapp/files', haeu.`material_receipt`) AS ae_material_imageurl, " + + " CONCAT('https://gccservices.in/gccofficialapp/files', haeu.`fir_image`) AS ae_fir_imageurl " + + "FROM " + + " `asset_list` al " + + "LEFT JOIN " + + " `hoardings_info` hi ON al.id = hi.asset_id " + + "LEFT JOIN " + + " `asset_category` ac ON ac.id = al.category_id " + + "LEFT JOIN " + + " `hoarding_info_type` hit ON hit.id = hi.hitid " + + "LEFT JOIN " + + " `hoarding_ae_update` haeu ON haeu.asset_id = hi.asset_id " + + "WHERE " + + " al.`isactive` = 1 " + + " AND al.`isdelete` = 0 " + + " AND al.`ward` = ? " + + " AND hi.`hitid` = ? " + + " AND DATE(al.`cdate`) BETWEEN STR_TO_DATE(?, '%d-%m-%Y') AND STR_TO_DATE(?, '%d-%m-%Y') " + + " AND hit.`name` IS NOT NULL " + + "GROUP BY " + + " al.`id` " + + "ORDER BY" + + " al.`id` DESC"; + + List> result = jdbcHoardingsTemplate.queryForList(sqlQuery, ward, hitid, fromDate, toDate); + Map response = new HashMap<>(); + response.put("status", 200); + response.put("message", "Main Report Data"); + response.put("data", result); + + return Collections.singletonList(response); + } +} diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/hoardings/services/package-info.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/hoardings/services/package-info.java new file mode 100644 index 0000000..309ee44 --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/hoardings/services/package-info.java @@ -0,0 +1 @@ +package in.gov.chennaicorporation.mobileservice.hoardings.services; \ No newline at end of file diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/nulm/controller/APINULMOfficerController.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/nulm/controller/APINULMOfficerController.java index 21c5563..a50508f 100644 --- a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/nulm/controller/APINULMOfficerController.java +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/nulm/controller/APINULMOfficerController.java @@ -70,5 +70,14 @@ public class APINULMOfficerController { ){ return nulmOfficerActivity.getStaffAttendanceListByDate(reporterId,specificDate); } + + @GetMapping(value="/getAttendanceListByStaff") + public List getAttendanceListByStaff(@RequestParam(value="Year") String year, + @RequestParam(value="Month") String month, @RequestParam(value="EmpId") int empId, + @RequestParam(value="AttendanceType") String attendanceType){ + + return nulmOfficerActivity.getAttendanceListByStaff(year, month, empId, attendanceType); + + } } diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/nulm/service/NULMOfficerActivity.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/nulm/service/NULMOfficerActivity.java index 1d777fc..e29a9c7 100644 --- a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/nulm/service/NULMOfficerActivity.java +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/nulm/service/NULMOfficerActivity.java @@ -350,4 +350,33 @@ public class NULMOfficerActivity { return Collections.singletonList(response); } + + public List getAttendanceListByStaff(String year, String month, int empId, String attendanceType) { + + String sqlQuery = null; + + if(attendanceType.equals("P")) { + + sqlQuery = "select DATE_FORMAT(indatetime, '%d-%m-%Y') as DATE from attendance where enrollment_id = '"+empId+"' " + + "and year(indatetime) = '"+year+"' and monthname(indatetime) = '"+month+"' "; + + } else if(attendanceType.equals("A")) { + + sqlQuery = "select DATE_FORMAT(leavedatetime, '%d-%m-%Y') as DATE from attendance where enrollment_id = '"+empId+"' " + + "and year(leavedatetime) = '"+year+"' and monthname(leavedatetime) = '"+month+"' "; + + } else if(attendanceType.equals("O")) { + + sqlQuery = "select DATE_FORMAT (oddatetime, '%d-%m-%Y') as DATE from attendance where enrollment_id = '"+empId+"' " + + "and year(oddatetime) = '"+year+"' and monthname(oddatetime) = '"+month+"' "; + } + + // Execute the query + List result = jdbcNULMTemplate.queryForList( sqlQuery, String.class); + + if(result.isEmpty()) + return Collections.singletonList("No Data Found"); + else + return result; + } } diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/penalty/controller/APICattleCatchController.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/penalty/controller/APICattleCatchController.java index 4438617..a4f8b4b 100644 --- a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/penalty/controller/APICattleCatchController.java +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/penalty/controller/APICattleCatchController.java @@ -44,10 +44,16 @@ public class APICattleCatchController { @GetMapping("/step1list") public List step1list(@RequestParam MultiValueMap formData, - @RequestParam(value = "orderid", required = false) String loginId) { + @RequestParam(value = "loginid", required = false) String loginId) { return cattleCatchService.step1list(formData,loginId); } + @GetMapping(value = "/getdepotlist") + public List getdepotlist(@RequestParam(value = "latitude", required = false) String latitude, + @RequestParam(value = "longitude", required = false) String longitude) { + return cattleCatchService.getdepotlist(latitude, longitude); + } + @PostMapping(value="/step2") // Move Catched cattle to depot public List step2(@RequestParam MultiValueMap formData, @RequestParam(value = "cinfoid", required = false) String cinfoid, @@ -68,8 +74,8 @@ public class APICattleCatchController { @GetMapping("/step2list") public List step2list(@RequestParam MultiValueMap formData, - @RequestParam(value = "orderid", required = false) String orderid) { - return cattleCatchService.step2list(formData,orderid); + @RequestParam(value = "depotid", required = true) String depotid) { + return cattleCatchService.step2list(formData,depotid); } @PostMapping(value="/step3") // Generate Fine Chellan when Violator is Available @@ -83,14 +89,14 @@ public class APICattleCatchController { @RequestParam(value = "streetName", required = false) String streetName, @RequestParam(value = "loginId", required = false) String loginId, @RequestParam(value = "remarks", required = false) String remarks, - //@RequestParam(value = "isviolatorAvailable", required = false) String isviolatorAvailable, + @RequestParam(value = "depotid", required = false) String depotid, @RequestParam(value = "violatorName", required = false) String violatorName, @RequestParam(value = "violatorPhone", required = false) String violatorPhone, @RequestParam(value = "fineAmount", required = false) String fineAmount, @RequestParam(value = "file", required = false) MultipartFile file ) { return cattleCatchService.step3(formData, cinfoids, latitude, longitude, zone, ward, streeId, - streetName, loginId,remarks,violatorName,violatorPhone,fineAmount,file); + streetName, loginId,remarks,violatorName,violatorPhone,fineAmount,depotid,file); } @GetMapping("/getChallanPOSData") @@ -100,11 +106,25 @@ public class APICattleCatchController { return cattleCatchService.getChallanPOSData(formData,orderid,loginid); } + @GetMapping("/updateSerialNumber") + public List updateSerialNumber(@RequestParam MultiValueMap formData, + @RequestParam(value = "tid", required = true) String tid, + @RequestParam(value = "mid", required = true) String mid, + @RequestParam(value = "serialNumber", required = true) String serialNumber, + @RequestParam(value = "orderid", required = true) String orderid) { + return cattleCatchService.updateSerialNumber(formData,tid, mid, serialNumber, orderid); + } + @PostMapping("/storeBankTransaction") public List storeBankTransaction(@RequestBody Map transactionData) { return cattleCatchService.storeBankTransaction(transactionData); } + @PostMapping("/storeFailedBankTransaction") + public List storeFailedBankTransaction(@RequestBody Map transactionData) { + return cattleCatchService.storeFailedBankTransaction(transactionData); + } + @GetMapping("/step3list") public List step3list(@RequestParam MultiValueMap formData, @RequestParam(value = "loginid", required = true) String loginid) { @@ -128,4 +148,53 @@ public class APICattleCatchController { streetName, loginId,remarks,file); } + @GetMapping("/depotReport") + public List DepotReport(@RequestParam MultiValueMap formData, + @RequestParam(value = "fromDate", required = true) String fromDate, + @RequestParam(value = "toDate", required = true) String toDate, + @RequestParam(value = "loginid", required = false) String loginid) { + return cattleCatchService.depotReport(formData,fromDate,toDate,loginid); + } + + @GetMapping("/zoneReport") + public List zoneReport(@RequestParam MultiValueMap formData, + @RequestParam(value = "fromDate", required = true) String fromDate, + @RequestParam(value = "toDate", required = true) String toDate, + @RequestParam(value = "depotid", required = true) String depotid, + @RequestParam(value = "loginid", required = false) String loginid) { + return cattleCatchService.zoneReport(formData,fromDate,toDate,depotid,loginid); + } + + @GetMapping("/wardReport") + public List zoneReport(@RequestParam MultiValueMap formData, + @RequestParam(value = "fromDate", required = true) String fromDate, + @RequestParam(value = "toDate", required = true) String toDate, + @RequestParam(value = "zone", required = true) String zone, + @RequestParam(value = "depotid", required = true) String depotid, + @RequestParam(value = "loginid", required = false) String loginid) { + return cattleCatchService.wardReport(formData,fromDate,toDate,zone,depotid,loginid); + } + + @GetMapping("/inListReport") + public List inListReport(@RequestParam MultiValueMap formData, + @RequestParam(value = "fromDate", required = true) String fromDate, + @RequestParam(value = "toDate", required = true) String toDate, + @RequestParam(value = "zone", required = true) String zone, + @RequestParam(value = "ward", required = true) String ward, + @RequestParam(value = "depotid", required = true) String depotid, + @RequestParam(value = "loginid", required = false) String loginid) { + return cattleCatchService.inListReport(formData,fromDate,toDate,zone,ward,depotid,loginid); + } + + @GetMapping("/outListReport") + public List outListReport(@RequestParam MultiValueMap formData, + @RequestParam(value = "fromDate", required = true) String fromDate, + @RequestParam(value = "toDate", required = true) String toDate, + @RequestParam(value = "zone", required = true) String zone, + @RequestParam(value = "ward", required = true) String ward, + @RequestParam(value = "depotid", required = true) String depotid, + @RequestParam(value = "loginid", required = false) String loginid) { + return cattleCatchService.outListReport(formData,fromDate,toDate,zone,ward,depotid,loginid); + } + } diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/penalty/controller/APIPenaltyControllerPOS.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/penalty/controller/APIPenaltyControllerPOS.java index 09946a5..9acc048 100644 --- a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/penalty/controller/APIPenaltyControllerPOS.java +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/penalty/controller/APIPenaltyControllerPOS.java @@ -64,11 +64,16 @@ public class APIPenaltyControllerPOS { @RequestParam(value = "loginId", required = false) String loginId, @RequestParam(value = "violatorName", required = false) String violatorName, @RequestParam(value = "violatorPhone", required = false) String violatorPhone, + @RequestParam(value = "violatorCompany", required = false) String violatorCompany, @RequestParam(value = "ton", required = false) String ton, @RequestParam(value = "amount", required = false) String amount, + @RequestParam(value = "tid", required = false) String tid, + @RequestParam(value = "mid", required = false) String mid, + @RequestParam(value = "serialNumber", required = false) String serialNumber, @RequestParam(value = "file", required = false) MultipartFile file ) { - return penaltyServicePOS.generateChallanPOS(formData, categoryId, latitude, longitude, zone, ward,loginId,violatorName,violatorPhone,ton,amount,file); + return penaltyServicePOS.generateChallanPOS(formData, categoryId, latitude, longitude, zone, ward, + loginId, violatorName, violatorPhone, violatorCompany, ton, amount, tid, mid, serialNumber, file); } @PostMapping("/storeBankTransaction") @@ -76,8 +81,13 @@ public class APIPenaltyControllerPOS { return penaltyServicePOS.storeBankTransaction(transactionData); } + @PostMapping("/storeFailedBankTransaction") + public List storeFailedBankTransaction(@RequestBody Map transactionData) { + return penaltyServicePOS.storeFailedBankTransaction(transactionData); + } + @PostMapping(value="/storeOfflineTransaction") - public List generateChallan(@RequestParam MultiValueMap formData, + public List generateOfflineChallan(@RequestParam MultiValueMap formData, @RequestParam(value = "transactionResponseStatus", required = false) String transactionResponseStatus, @RequestParam(value = "bankName", required = false) String bankName, @RequestParam(value = "transactionAmount", required = false) String transactionAmount, diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/penalty/service/CattleCatchService.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/penalty/service/CattleCatchService.java index 4be3265..fc13cad 100644 --- a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/penalty/service/CattleCatchService.java +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/penalty/service/CattleCatchService.java @@ -14,6 +14,7 @@ import java.sql.SQLException; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; +import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -121,7 +122,7 @@ public class CattleCatchService { return byteArrayOutputStream.toByteArray(); } - public String fileUpload(String name, String id, MultipartFile file) { + public String fileUpload(String name, String id, String folder, MultipartFile file) { int lastInsertId = 0; // Set the file path where you want to save it @@ -130,7 +131,7 @@ public class CattleCatchService { var year =DateTimeUtil.getCurrentYear(); var month =DateTimeUtil.getCurrentMonth(); - uploadDirectory = uploadDirectory + serviceFolderName + year +"/"+month+"/"; + uploadDirectory = uploadDirectory + serviceFolderName + year +"/"+month+"/"+folder+"/"; try { // Create directory if it doesn't exist @@ -147,7 +148,7 @@ public class CattleCatchService { String filePath = uploadDirectory + "/" + fileName; - String filepath_txt = "/"+serviceFolderName + year +"/"+month+"/"+fileName; + String filepath_txt = "/"+serviceFolderName + year +"/"+month+"/"+folder+"/"+fileName; // Create a new Path object Path path = Paths.get(filePath); @@ -192,7 +193,7 @@ public class CattleCatchService { Map response = new HashMap<>(); int lastInsertId = 0; - String image = fileUpload("cc_step1",category_id,file); + String image = fileUpload("cc_step1_catch",category_id,"catch",file); String sqlQuery = "INSERT INTO `cc_step1`(`category_id`, `image`, `latitude`, `longitude`, " + "`zone`, `ward`, `streetid`, `streetname`, `catch_by`,`remarks`) " @@ -233,7 +234,7 @@ public class CattleCatchService { System.out.println("Cattle caught successfully! Insert ID: " + generatedId); } else { response.put("status", "error"); - response.put("message", "Failed to insert a new Penalty (Chellan)."); + response.put("message", "Failed to insert a new caught (Info)."); } } catch (DataAccessException e) { System.out.println("Data Access Exception:"); @@ -264,24 +265,41 @@ public class CattleCatchService { String sqlQuery = "SELECT *, " + "CONCAT('"+fileBaseUrl+"/gccofficialapp/files',`image`) as imageurl " - + " From `cc_step1` WHERE (`isactive`=1 AND `isdelete`=0)"; + + " From `cc_step1` WHERE (`isactive`=1 AND `isdelete`=0 AND `checkin`=0)"; if(loginid!=null && !loginid.isEmpty() && !loginid.isBlank()) { sqlQuery= sqlQuery +" AND `catch_by`='"+loginid+"'"; } - sqlQuery = sqlQuery + " LIMIT 1"; + //sqlQuery = sqlQuery + " LIMIT 1"; //System.out.println(sqlQuery); List> result = jdbcPenaltyTemplate.queryForList(sqlQuery); Map response = new HashMap<>(); response.put("status", 200); - response.put("message", "Challan Details"); + response.put("message", "List for ChekIn"); response.put("data", result); - return result; + return Collections.singletonList(response); } + @Transactional + public List> getdepotlist(String latitude, String longitude) { + String sqlQuery = ""; + + sqlQuery = "SELECT * " + "FROM depot_list " + "WHERE (isactive=1 AND isdelete=0) AND " + + " ((6371008.8 * acos( ROUND(cos(radians(?)) * cos(radians(latitude)) * cos(radians(longitude) - radians(?)) + sin(radians(?)) * sin(radians(latitude)), 9) )) < 500)"; + List> result = jdbcPenaltyTemplate.queryForList(sqlQuery, + new Object[] { latitude, longitude, latitude }); + Map response = new HashMap<>(); + + response.put("status", 200); + response.put("message", "Request Information"); + response.put("Data", result); + + return Collections.singletonList(response); + } + @Transactional public List> step2( MultiValueMap formData, @@ -300,7 +318,7 @@ public class CattleCatchService { Map response = new HashMap<>(); int lastInsertId = 0; - String image = fileUpload("cc_step2",cinfoid,file); + String image = fileUpload("cc_step2_in",cinfoid,"checkin",file); String sqlQuery = "INSERT INTO `cc_step2`(`cinfoid`,`image`, `latitude`, `longitude`, " + "`zone`, `ward`, `streetid`, `streetname`, `in_by`,`remarks`,`depotid`) " @@ -340,6 +358,8 @@ public class CattleCatchService { response.put("status", "success"); response.put("message", "Cattle successfully checked into the depot!"); System.out.println("Cattle successfully checked into the depot! Insert ID: " + generatedId); + updateStep1(cinfoid); + } else { response.put("status", "error"); response.put("message", "Failed to checked into the depot"); @@ -366,29 +386,87 @@ public class CattleCatchService { return Collections.singletonList(response); } + public String updateStep1(String cinfoid) { + String sqlQuery = "UPDATE `cc_step1` SET checkin = 1 WHERE id = ? LIMIT 1"; + //System.out.println(sqlQuery); + jdbcPenaltyTemplate.update(sqlQuery, cinfoid); + return "success"; + } + @Transactional public List> step2list( MultiValueMap formData, - String orderid) { + String depotid) { - String sqlQuery = "SELECT *, " - + "CONCAT('"+fileBaseUrl+"/gccofficialapp/files',`image`) as imageurl " - + " From `cc_step2` WHERE (`isactive`=1 AND `isdelete`=0) AND `status`='in'"; + String sqlQuery = "SELECT s2.`id`, s2.`cinfoid`, s2.`depotid`, s2.`in_by`, " + + "DATE_FORMAT(s2.`in_date`, '%d-%m-%Y %H:%i') AS in_date, " + + "s2.`remarks` as in_remarks, s1.catch_date, s1.catch_by, " + + "s1.latitude, s1.longitude, s1.zone, s1.ward, s1.streetid, s1.streetname, s1.remarks as catch_remarks," + + "DATEDIFF(CURDATE(), in_date) AS days_since_in_date, " + + "CONCAT('"+fileBaseUrl+"/gccofficialapp/files',s2.`image`) as in_imageurl, " + + "CONCAT('"+fileBaseUrl+"/gccofficialapp/files',s1.`image`) as catch_imageurl " + + "From `cc_step1` s1,`cc_step2` s2 WHERE (s1.`isactive`=1 AND s1.`isdelete`=0) AND (s1.id=s2.cinfoid) " + + "AND s2.`status`='in'"; - if(orderid!=null && !orderid.isEmpty() && !orderid.isBlank()) { - sqlQuery= sqlQuery +" "; + if(depotid!=null && !depotid.isEmpty() && !depotid.isBlank()) { + sqlQuery= sqlQuery +" AND depotid=?"; } + System.out.println(sqlQuery); + List> result = jdbcPenaltyTemplate.queryForList(sqlQuery,depotid); + /* //sqlQuery = sqlQuery + " LIMIT 1"; System.out.println(sqlQuery); - List> result = jdbcPenaltyTemplate.queryForList(sqlQuery); + List> result = jdbcPenaltyTemplate.queryForList(sqlQuery,depotid); Map response = new HashMap<>(); response.put("status", 200); - response.put("message", "Challan Details"); + response.put("message", "CheckIn List"); response.put("data", result); return result; + */ + // Initialize response list + List> detailedResult = new ArrayList<>(); + + // Iterate through the depots and get additional details + for (Map cattle : result) { + // Extract days from the current cattle entry + Object noOfDayObject = cattle.get("days_since_in_date"); + if (noOfDayObject == null) { + continue; // Skip if of days is missing + } + String noofdays = noOfDayObject.toString(); // Assuming noOfDayObject is your object containing the days + int days = Integer.parseInt(noofdays); // Convert String to integer + + int amount = 5000; + int extraDays = 0; + int finalAmount; + + if (days <= 2) { + finalAmount = amount; // No extra charge + } else { + extraDays = days - 2; // Calculate extra days + finalAmount = amount + (extraDays * 1000); // Add extra charges + } + + System.out.println("Final Amount: " + finalAmount); + + // Add counts to the current depot details + Map detailedDepot = new HashMap<>(cattle); + detailedDepot.put("fineAmount", finalAmount); + + // Add detailed depot to the response list + detailedResult.add(detailedDepot); + } + + // Prepare response + Map response = new HashMap<>(); + response.put("status", 200); + response.put("message", "CheckIn List"); + response.put("data", detailedResult); + + return Collections.singletonList(response); } @Transactional @@ -403,10 +481,10 @@ public class CattleCatchService { String streetName, String loginId, String remarks, - //String isviolatorAvailable, String violatorName, String violatorPhone, String fineAmount, + String depotid, MultipartFile file) { Map response = new HashMap<>(); @@ -419,8 +497,8 @@ public class CattleCatchService { String sqlQuery = "INSERT INTO `cc_step3`(`cinfoids`, `image`, `latitude`, `longitude`, " + "`zone`, `ward`, `streetid`, `streetname`, `challan_by`,`remarks`, " - + " `violator_name`, `violator_phone`,`fine_amount`,`orderid`) " - + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + + " `violator_name`, `violator_phone`,`fine_amount`,`orderid`,`depotid`) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; KeyHolder keyHolder = new GeneratedKeyHolder(); @@ -443,6 +521,7 @@ public class CattleCatchService { ps.setString(12, violatorPhone); ps.setString(13, fineAmount); ps.setString(14, orderid); + ps.setString(15, depotid); return ps; } }, keyHolder); @@ -500,7 +579,7 @@ public class CattleCatchService { //+ "CONCAT('"+fileBaseUrl+"/gccofficialapp/files',`image`) as imageurl, " + "`latitude`, `longitude`, `zone`, `ward`, " + "`challan_by`, `violator_name`, `violator_phone`, " - + "`fine_amount`,`orderid`,`status` From `cc_step3` WHERE (`isactive`=1 AND `isdelete`=0) AND `status`='unpaid'"; + + "`fine_amount`,`orderid`,`status` From `cc_step3` WHERE (`isactive`=1 AND `isdelete`=0) AND (`status` <> 'Transaction success' AND `status` <> 'out') "; if(orderid!=null && !orderid.isEmpty() && !orderid.isBlank()) { sqlQuery= sqlQuery +" AND `orderid`='"+orderid+"'"; @@ -518,9 +597,24 @@ public class CattleCatchService { response.put("message", "Challan Details"); response.put("data", result); - return result; + return Collections.singletonList(response); } + @Transactional + public List> updateSerialNumber( + MultiValueMap formData, + String tid, + String mid, + String serialNumber, + String orderid){ + String sqlQuery = "UPDATE cc_step3 SET tid = ?, mid = ?, serial_number = ? WHERE orderid = ? LIMIT 1"; + jdbcPenaltyTemplate.update(sqlQuery, tid, mid, serialNumber, orderid); + Map response = new HashMap<>(); + response.put("status", 200); + response.put("message", "Serial Number updated successfully"); + return Collections.singletonList(response); + } + @Transactional public List> storeBankTransaction(Map transactionData) { @@ -566,6 +660,189 @@ public class CattleCatchService { KeyHolder keyHolder = new GeneratedKeyHolder(); + try { + int affectedRows = jdbcPenaltyTemplate.update(new PreparedStatementCreator() { + @Override + public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { + PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[]{"id"}); + ps.setString(1, mid); + ps.setString(2, tid); + ps.setString(3, txnId); + ps.setString(4, bankName); + ps.setString(5, batchNumber); + ps.setDouble(6, transactionAmount); + ps.setString(7, transactionTitle); + ps.setString(8, txnAID); + ps.setString(9, txnApprCode); + ps.setString(10, txnCardNo); + ps.setString(11, txnCardType); + ps.setString(12, txnDate); + ps.setString(13, txnInvoice); + ps.setString(14, txnMode); + ps.setString(15, txnRefNo); + ps.setString(16, txnTC); + ps.setString(17, txnTSI); + ps.setString(18, txnTVR); + ps.setString(19, txnTime); + return ps; + } + }, keyHolder); + + if (affectedRows > 0) { + Number generatedId = keyHolder.getKey(); + lastInsertId = (generatedId != null) ? generatedId.intValue() : 0; + + // Fetch inserted data for response, joining `penalty_challan` and `bank_transactions` + /* + String sqlQuery_joined = "SELECT pc.category_id, CONCAT('" + fileBaseUrl + "/gccofficialapp/files', pc.image) as imageurl, " + + "pc.latitude, pc.longitude, pc.zone, pc.ward, pc.challan_by, " + + "pc.violator_name, pc.violator_phone, pc.fine_amount, pc.orderid, pc.status, " + + "bt.mid, bt.tid, bt.txnId, bt.bankName, bt.batchNumber, bt.transactionAmount, bt.transactionTitle, " + + "bt.txnCardNo, bt.txnDate, bt.txnInvoice, bt.txnMode, bt.txnRefNo " + + "FROM cc_step3 pc " + + "LEFT JOIN bank_transactions bt ON pc.orderid = bt.txnId " + + "WHERE pc.isactive = 1 AND pc.isdelete = 0 AND bt.id = ? LIMIT 1"; + */ + + String sqlQuery_joined = "SELECT" + + " pc.`id`, " + + " pc.`cinfoids`, " + + " pc.`challan_by`, " + + " DATE_FORMAT(pc.`challan_date`, '%d-%m-%Y %H:%i') AS challan_date, " + + " pc.`latitude`, " + + " pc.`longitude`, " + + " pc.`zone`, " + + " pc.`ward`, " + + " pc.`streetid`, " + + " pc.`streetname`, " + + " pc.`image`, " + + " pc.`remarks`, " + + " pc.`status`, " + + " pc.`isactive`, " + + " pc.`isdelete`, " + + " pc.`violator_name`, " + + " pc.`violator_phone`, " + + " pc.`fine_amount`, " + + " pc.`orderid`, " + + " pc.`depotid`, " + + " LENGTH(pc.cinfoids) - LENGTH(REPLACE(pc.cinfoids, ',', '')) + 1 AS cattlecount, " + + " CONCAT('https://gccservices.in/gccofficialapp/files', pc.`image`) AS imageurl, " + + " bt.mid, " + + " bt.tid, " + + " bt.txnId, " + + " bt.bankName, " + + " bt.batchNumber, " + + " bt.transactionAmount, " + + " bt.transactionTitle, " + + " bt.txnCardNo, " + + " bt.txnDate, " + + " bt.txnInvoice, " + + " bt.txnMode, " + + " bt.txnRefNo " + + "FROM " + + " `cc_step3` pc " + + "LEFT JOIN " + + " `bank_transactions` bt ON pc.orderid = bt.txnId " + + "WHERE " + + " (pc.`isactive` = 1 AND pc.`isdelete` = 0) " + + " AND (bt.id = ?)"; + + System.out.println(sqlQuery_joined); + // Execute the query + List> result = jdbcPenaltyTemplate.queryForList(sqlQuery_joined, lastInsertId); + + response.put("status", 200); + response.put("message", "Transaction stored successfully!"); + response.put("data", result); + + updatePaymentStatus(txnId, transactionResponseStatus); + + } else { + response.put("status", 201); + response.put("message", "Failed to store the transaction."); + response.put("data", ""); + } + } catch (DataAccessException e) { + response.put("status", 500); + response.put("message", "Database error while storing transaction."); + response.put("error", e.getMessage()); + e.printStackTrace(); // This will give you more detail in logs + } + } else { + response.put("status", 400); + response.put("message", "Transaction failed or invalid status."); + } + + return Collections.singletonList(response); + } + + @Transactional + public List> storeFailedBankTransaction(Map transactionData) { + + Map response = new HashMap<>(); + int lastInsertId = 0; + + // Extract data from the JSON object + String transactionResponseStatus = (String) transactionData.get("transactionResponseStatus"); + + // Check if the transaction was successful + if ("Transaction cancelled".equalsIgnoreCase(transactionResponseStatus)) { + + String mid = (String) transactionData.get("mid"); + String tid = (String) transactionData.get("tid"); + String txnId = (String) transactionData.get("txnId"); + + // Fetch nested transaction response data + Map txnResponseData = (Map) transactionData.get("txnResponseData"); + + String bankName = (String) txnResponseData.get("bankName"); + String batchNumber = (String) txnResponseData.get("batchNumber"); + String transactionTitle = (String) txnResponseData.get("transactionTitle"); + String txnAID = (String) txnResponseData.get("txnAID"); + String txnApprCode = (String) txnResponseData.get("txnApprCode"); + String txnCardNo = (String) txnResponseData.get("txnCardNo"); + String txnCardType = (String) txnResponseData.get("txnCardType"); + String txnDate = (String) txnResponseData.get("txnDate"); + String txnInvoice = (String) txnResponseData.get("txnInvoice"); + String txnMode = (String) txnResponseData.get("txnMode"); + String txnRefNo = (String) txnResponseData.get("txnRefNo"); + String txnTC = (String) txnResponseData.get("txnTC"); + String txnTSI = (String) txnResponseData.get("txnTSI"); + String txnTVR = (String) txnResponseData.get("txnTVR"); + String txnTime = (String) txnResponseData.get("txnTime"); + + // Convert transaction amount properly + //Double transactionAmount = Double.valueOf((String) txnResponseData.get("transactionAmount")); + + // Get the transactionAmount from txnResponseData + String transactionAmountStr = (String) txnResponseData.get("transactionAmount"); + + // Check if the transactionAmount is not null and not empty before converting + Double transactionAmountTemp = null; + + if (transactionAmountStr != null && !transactionAmountStr.trim().isEmpty()) { + try { + // Convert the valid string to a Double + transactionAmountTemp = Double.valueOf(transactionAmountStr); + } catch (NumberFormatException e) { + // Handle the case where the string cannot be parsed to a Double // Log the error or throw a custom exception + System.out.println("Error: Unable to parse transactionAmount to Double. " + e.getMessage()); + transactionAmountTemp = 0.0; // Set to a default value or handle as needed + } + } else { + // Handle the case where transactionAmount is empty or null + transactionAmountTemp = 0.0; // Default value or handle as needed + } + + Double transactionAmount = transactionAmountTemp; + + String sqlQuery = "INSERT INTO bank_failed_transactions (mid, tid, txnId, bankName, batchNumber, transactionAmount, " + + "transactionTitle, txnAID, txnApprCode, txnCardNo, txnCardType, txnDate, txnInvoice, txnMode, txnRefNo, " + + "txnTC, txnTSI, txnTVR, txnTime) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; + + KeyHolder keyHolder = new GeneratedKeyHolder(); + try { int affectedRows = jdbcPenaltyTemplate.update(new PreparedStatementCreator() { @Override @@ -601,6 +878,7 @@ public class CattleCatchService { updatePaymentStatus(txnId, transactionResponseStatus); // Fetch inserted data for response, joining `penalty_challan` and `bank_transactions` + /* String sqlQuery_joined = "SELECT pc.category_id, CONCAT('" + fileBaseUrl + "/gccofficialapp/files', pc.image) as imageurl, " + "pc.latitude, pc.longitude, pc.zone, pc.ward, pc.challan_by, " + "pc.violator_name, pc.violator_phone, pc.fine_amount, pc.orderid, pc.status, " @@ -609,10 +887,54 @@ public class CattleCatchService { + "FROM cc_step3 pc " + "LEFT JOIN bank_transactions bt ON pc.orderid = bt.txnId " + "WHERE pc.isactive = 1 AND pc.isdelete = 0 AND bt.id = ? LIMIT 1"; + */ + + String sqlQuery_joined = "SELECT" + + " pc.`id`, " + + " pc.`cinfoids`, " + + " pc.`challan_by`, " + + " DATE_FORMAT(pc.`challan_date`, '%d-%m-%Y %H:%i') AS challan_date, " + + " pc.`latitude`, " + + " pc.`longitude`, " + + " pc.`zone`, " + + " pc.`ward`, " + + " pc.`streetid`, " + + " pc.`streetname`, " + + " pc.`image`, " + + " pc.`remarks`, " + + " pc.`status`, " + + " pc.`isactive`, " + + " pc.`isdelete`, " + + " pc.`violator_name`, " + + " pc.`violator_phone`, " + + " pc.`fine_amount`, " + + " pc.`orderid`, " + + " pc.`depotid`, " + + " LENGTH(pc.cinfoids) - LENGTH(REPLACE(pc.cinfoids, ',', '')) + 1 AS cattlecount, " + + " CONCAT('https://gccservices.in/gccofficialapp/files', pc.`image`) AS imageurl, " + + " bt.mid, " + + " bt.tid, " + + " bt.txnId, " + + " bt.bankName, " + + " bt.batchNumber, " + + " bt.transactionAmount, " + + " bt.transactionTitle, " + + " bt.txnCardNo, " + + " bt.txnDate, " + + " bt.txnInvoice, " + + " bt.txnMode, " + + " bt.txnRefNo " + + "FROM " + + " `cc_step3` pc " + + "LEFT JOIN " + + " `bank_failed_transactions` bt ON pc.orderid = bt.txnId " + + "WHERE " + + " (pc.`isactive` = 1 AND pc.`isdelete` = 0) " + + " AND (bt.id = ?)"; + System.out.println(sqlQuery_joined); // Execute the query List> result = jdbcPenaltyTemplate.queryForList(sqlQuery_joined, lastInsertId); - response.put("status", 200); response.put("message", "Transaction stored successfully!"); response.put("data", result); @@ -647,9 +969,14 @@ public class CattleCatchService { MultiValueMap formData, String loginid) { - String sqlQuery = "SELECT *, " + String sqlQuery = "SELECT `id`, `cinfoids`, `challan_by`, " + + "DATE_FORMAT(`challan_date`, '%d-%m-%Y %H:%i') AS challan_date, " + + "`latitude`, `longitude`, `zone`, `ward`, `streetid`, `streetname`, " + + "`image`, `remarks`, `status`, `isactive`, `isdelete`, `violator_name`, " + + "`violator_phone`, `fine_amount`, `orderid`, `depotid`, " + + "LENGTH(cinfoids) - LENGTH(REPLACE(cinfoids, ',', '')) + 1 AS cattlecount, " + "CONCAT('"+fileBaseUrl+"/gccofficialapp/files',`image`) as imageurl " - + " From `cc_step3` WHERE (`isactive`=1 AND `isdelete`=0) AND `status`<>'unpaid'"; + + " From `cc_step3` WHERE (`isactive`=1 AND `isdelete`=0) AND (`status`<> 'unpaid' AND `status`<> 'out')"; if(loginid!=null && !loginid.isEmpty() && !loginid.isBlank()) { sqlQuery= sqlQuery +" AND `challan_by`='"+loginid+"'"; @@ -664,7 +991,7 @@ public class CattleCatchService { response.put("message", "Challan Details"); response.put("data", result); - return result; + return Collections.singletonList(response); } @Transactional @@ -684,7 +1011,7 @@ public class CattleCatchService { Map response = new HashMap<>(); int lastInsertId = 0; - String image = fileUpload("cc_step2",cinfoid,file); + String image = fileUpload("cc_step4_out",cinfoid,"out",file); String sqlQuery = "INSERT INTO `cc_step4`(`cinfoid`,`image`, `latitude`, `longitude`, " + "`zone`, `ward`, `streetid`, `streetname`, `out_by`,`remarks`) " @@ -708,21 +1035,19 @@ public class CattleCatchService { ps.setString(8, streetName); ps.setString(9, loginId); ps.setString(10, remarks); - //ps.setString(11, isviolatorAvailable); - //ps.setString(12, violatorName); - //ps.setString(13, violatorPhone); - //ps.setString(14, ton); return ps; } }, keyHolder); if (affectedRows > 0) { + updateOutStatus(cinfoid,"out"); Number generatedId = keyHolder.getKey(); lastInsertId = (generatedId != null) ? generatedId.intValue() : 0; response.put("insertId", lastInsertId); response.put("status", "success"); response.put("message", "Cattle successfully checked out from the depot!"); System.out.println("Cattle successfully checked out from the depot! Insert ID: " + generatedId); + } else { response.put("status", "error"); response.put("message", "Failed to checked out from the depot"); @@ -749,15 +1074,402 @@ public class CattleCatchService { return Collections.singletonList(response); } + public String updateOutStatus(String id, String status) { + String sqlQuery = "UPDATE cc_step3 SET status = ? WHERE id = ? LIMIT 1"; + jdbcPenaltyTemplate.update(sqlQuery, status, id); + return "success"; + } + /* + @Transactional + public List> DepotReport( + MultiValueMap formData, + String fromDate, + String toDate, + String loginid) { + + String sqlQuery = "SELECT * FROM `depot_list` where `isactive`=1 AND `isdelete`=0"; + List> result = jdbcPenaltyTemplate.queryForList(sqlQuery); + //System.out.println(sqlQuery); + + String depotid="1"; + + String sqlQuery_total = "SELECT count(id) as Total FROM `depot_list` where (`isactive`=1 AND `isdelete`=0) AND (`depotid`=?)"; + List> resultTotal = jdbcPenaltyTemplate.queryForList(sqlQuery_total,depotid); + + String sqlQuery_paid = "SELECT count(s3.id) as TotalPaid FROM `cc_step3` s3," + + "where (`isactive`=1 AND `isdelete`=0) AND s3.`depotid`=?"; + List> resultPaid = jdbcPenaltyTemplate.queryForList(sqlQuery_total,depotid); + + String sqlQuery_out = "SELECT count(s4.id) as TotalPaid FROM `cc_step4` s4,`cc_step3` s3," + + "where (`isactive`=1 AND `isdelete`=0) AND s3.`id`= s4.cinfoid AND s3.`depotid`=?"; + List> resultOut = jdbcPenaltyTemplate.queryForList(sqlQuery_total,depotid); + + Map response = new HashMap<>(); + response.put("status", 200); + response.put("message", "Zone List Details"); + response.put("data", result); + + return result; + } + */ + @Transactional + public List> depotReport( + MultiValueMap formData, + String fromDate, + String toDate, + String loginid) { + + // Fetch depot list + String sqlQuery = "SELECT * FROM `depot_list` WHERE (`isactive`=1 AND `isdelete`=0)"; + List> result = jdbcPenaltyTemplate.queryForList(sqlQuery); + + // Initialize response list + List> detailedResult = new ArrayList<>(); + + // Iterate through the depots and get additional details + for (Map depot : result) { + // Extract depotid from the current depot entry + Object depotIdObject = depot.get("id"); + if (depotIdObject == null) { + continue; // Skip if depotid is missing + } + String depotid = depotIdObject.toString(); + System.out.println("depotid : "+depotid); + // Fetch total count for this depot + String sqlQuery_total = "SELECT count(id) as Total FROM `cc_step2` " + + "WHERE (`isactive`=1 AND `isdelete`=0) " + + "AND (`depotid`=? AND DATE(in_date) BETWEEN STR_TO_DATE(?, '%d-%m-%Y') AND STR_TO_DATE(?, '%d-%m-%Y'))"; + List> resultTotal = jdbcPenaltyTemplate.queryForList(sqlQuery_total, depotid,fromDate,toDate); + /* + // Fetch total paid count for this depot + String sqlQuery_paid = "SELECT count(s3.id) as TotalPaid FROM `cc_step3` s3 " + + "WHERE (`isactive`=1 AND `isdelete`=0) AND (s3.`depotid`=? AND s3.`status`<>'unpaid')"; + List> resultPaid = jdbcPenaltyTemplate.queryForList(sqlQuery_paid, depotid); +*/ + // Fetch total out count for this depot + String sqlQuery_out = "SELECT " + + "IFNULL(SUM(DISTINCT temp.cinfoid_count), 0) AS TotalOut " + + "FROM ( " + + " SELECT " + + " s2.cinfoid AS individual_cinfoid, " + + " COUNT(*) AS cinfoid_count " + + " FROM `cc_step2` s2 " + + " JOIN `cc_step3` s3 ON FIND_IN_SET(s2.cinfoid, s3.cinfoids) " + + " JOIN `cc_step4` s4 ON s3.`id` = s4.`cinfoid` " + + " WHERE (s2.`isactive` = 1 AND s2.`isdelete` = 0) " + + " AND (s2.`depotid` = ?) " + + " AND DATE(s4.out_date) BETWEEN STR_TO_DATE(?, '%d-%m-%Y') AND STR_TO_DATE(?, '%d-%m-%Y') " + + " " + + ") temp"; + List> resultOut = jdbcPenaltyTemplate.queryForList(sqlQuery_out, depotid,fromDate,toDate); + /* + // Fetch total paid count for this depot + String sqlQuery_pending = "SELECT count(s2.id) as TotalPending FROM `cc_step2` s2 " + + "WHERE (s2.`isactive`=1 AND s2.`isdelete`=0) AND (s2.`depotid`=? AND s2.`status`='in')"; + List> resultPending = jdbcPenaltyTemplate.queryForList(sqlQuery_pending, depotid); + */ + // Add counts to the current depot details + Map detailedDepot = new HashMap<>(depot); + detailedDepot.put("Total", resultTotal.isEmpty() ? 0 : resultTotal.get(0).get("Total")); + //detailedDepot.put("TotalPaid", resultPaid.isEmpty() ? 0 : resultPaid.get(0).get("TotalPaid")); + detailedDepot.put("TotalOut", resultOut.isEmpty() ? 0 : resultOut.get(0).get("TotalOut")); + //detailedDepot.put("TotalPending", resultPending.isEmpty() ? 0 : resultPending.get(0).get("TotalPending")); + + // Add detailed depot to the response list + detailedResult.add(detailedDepot); + } + + // Prepare response + Map response = new HashMap<>(); + response.put("status", 200); + response.put("message", "Depot List Details"); + response.put("data", detailedResult); + + return Collections.singletonList(response); + } + @Transactional public List> zoneReport( + MultiValueMap formData, + String fromDate, + String toDate, + String depotid, + String loginid) { + + // Fetch depot list + String sqlQuery = "SELECT s1.`zone`, dl.name FROM `cc_step1` s1,`cc_step2` s2,`depot_list` dl " + + "WHERE (s2.`isactive`=1 AND s2.`isdelete`=0) " + + "AND (s1.id=s2.cinfoid)" + + "AND (s2.`depotid`=? and dl.id=s2.`depotid`) " + + "AND DATE(s2.in_date) BETWEEN STR_TO_DATE(?, '%d-%m-%Y') AND STR_TO_DATE(?, '%d-%m-%Y') " + + "GROUP BY s1.`zone`, dl.name"; + List> result = jdbcPenaltyTemplate.queryForList(sqlQuery,depotid, fromDate, toDate); + + // Initialize response list + List> detailedResult = new ArrayList<>(); + + // Iterate through the depots and get additional details + for (Map depot : result) { + // Extract depotid from the current depot entry + Object zoneObject = depot.get("zone"); + if (zoneObject == null) { + continue; // Skip if depotid is missing + } + String zone = zoneObject.toString(); + System.out.println("zone : "+zone); + System.out.println("depotid : "+depotid); + + // Fetch total count for this depot + String sqlQuery_total = "SELECT count(s2.id) as Total FROM `cc_step1` s1,`cc_step2` s2 " + + "WHERE (s1.`isactive`=1 AND s1.`isdelete`=0) AND (s2.`depotid`=?)" + + "AND (s1.id=s2.cinfoid AND s1.zone=?) " + + "AND DATE(s2.in_date) BETWEEN STR_TO_DATE(?, '%d-%m-%Y') AND STR_TO_DATE(?, '%d-%m-%Y')"; + List> resultTotal = jdbcPenaltyTemplate.queryForList(sqlQuery_total, depotid, zone, fromDate, toDate); +/* + // Fetch total paid count for this depot + String sqlQuery_paid = "SELECT count(s3.id) as TotalPaid FROM `cc_step3` s3 " + + "WHERE (`isactive`=1 AND `isdelete`=0) AND (s3.`depotid`=? AND s3.`status`<>'unpaid') AND `zone`=?"; + List> resultPaid = jdbcPenaltyTemplate.queryForList(sqlQuery_paid, depotid,zone); +*/ + // Fetch total out count for this depot + String sqlQuery_out = "SELECT IFNULL(SUM(unique_cattle_count), 0) AS cattlecount " + + "FROM ( SELECT COUNT(DISTINCT s1.id) AS unique_cattle_count " + + "FROM cc_step1 s1 JOIN cc_step3 s3 ON FIND_IN_SET(s1.id, s3.cinfoids) " + + "JOIN cc_step4 s4 ON s3.id = s4.cinfoid " + + "WHERE s1.isactive = 1 AND s1.isdelete = 0 AND s3.depotid = ? " + + "AND s1.zone = ? AND DATE(s4.out_date) BETWEEN STR_TO_DATE(?, '%d-%m-%Y') " + + "AND STR_TO_DATE(?, '%d-%m-%Y') ) AS deduplicated_counts"; + List> resultOut = jdbcPenaltyTemplate.queryForList(sqlQuery_out, depotid,zone,fromDate,toDate); + + System.out.println(sqlQuery_out); + /* + + // Fetch total paid count for this depot + String sqlQuery_pending = "SELECT count(s2.id) as TotalPending FROM `cc_step2` s2 " + + "WHERE (s2.`isactive`=1 AND s2.`isdelete`=0) AND (s2.`depotid`=? AND s2.`status`='in')"; + List> resultPending = jdbcPenaltyTemplate.queryForList(sqlQuery_pending, depotid); +*/ + // Add counts to the current depot details + Map detailedDepot = new HashMap<>(depot); + detailedDepot.put("Total", resultTotal.isEmpty() ? 0 : resultTotal.get(0).get("Total")); + //detailedDepot.put("TotalPaid", resultPaid.isEmpty() ? 0 : resultPaid.get(0).get("TotalPaid")); + detailedDepot.put("TotalOut", resultOut.isEmpty() ? 0 : resultOut.get(0).get("cattlecount")); + //detailedDepot.put("TotalPending", resultPending.isEmpty() ? 0 : resultPending.get(0).get("TotalPending")); + + // Add detailed depot to the response list + detailedResult.add(detailedDepot); + } + + // Prepare response + Map response = new HashMap<>(); + response.put("status", 200); + response.put("message", "Zone List Details"); + response.put("data", detailedResult); + + return Collections.singletonList(response); + } + + @Transactional + public List> wardReport( + MultiValueMap formData, + String fromDate, + String toDate, + String zone, + String depotid, + String loginid) { + + // Fetch depot list + String sqlQuery = "SELECT s1.`zone`,s1.`ward`,dl.name FROM `cc_step1` s1,`cc_step2` s2,`depot_list` dl " + + "WHERE (s2.`isactive`=1 AND s2.`isdelete`=0) " + + "AND (s1.id=s2.cinfoid AND s1.zone=?)" + + "AND (s2.`depotid`=? and dl.id=s2.`depotid`) " + + "AND DATE(s2.in_date) BETWEEN STR_TO_DATE(?, '%d-%m-%Y') AND STR_TO_DATE(?, '%d-%m-%Y') " + + "GROUP BY s1.`zone`, s1.`ward`, dl.name"; + + List> result = jdbcPenaltyTemplate.queryForList(sqlQuery, zone, depotid, fromDate, toDate); + + // Initialize response list + List> detailedResult = new ArrayList<>(); + System.out.println("zone : "+zone); + System.out.println("depotid : "+depotid); + System.out.println("fromDate : "+fromDate); + System.out.println("toDate : "+toDate); + // Iterate through the depots and get additional details + for (Map depot : result) { + // Extract depotid from the current depot entry + Object wardObject = depot.get("ward"); + if (wardObject == null) { + continue; // Skip if depotid is missing + } + String ward = wardObject.toString(); + System.out.println("zone : "+zone); + System.out.println("depotid : "+depotid); + + // Fetch total count for this depot + String sqlQuery_total = "SELECT count(s2.id) as Total FROM `cc_step1` s1,`cc_step2` s2 " + + "WHERE (s1.`isactive`=1 AND s1.`isdelete`=0) AND (s2.`depotid`=?)" + + "AND (s1.id=s2.cinfoid AND s1.zone=? AND s1.ward=?) " + + "AND DATE(s2.in_date) BETWEEN STR_TO_DATE(?, '%d-%m-%Y') AND STR_TO_DATE(?, '%d-%m-%Y')"; + List> resultTotal = jdbcPenaltyTemplate.queryForList(sqlQuery_total, depotid, zone, ward,fromDate, toDate); +/* + // Fetch total paid count for this depot + String sqlQuery_paid = "SELECT count(s3.id) as TotalPaid FROM `cc_step3` s3 " + + "WHERE (`isactive`=1 AND `isdelete`=0) AND (s3.`depotid`=? AND s3.`status`<>'unpaid') AND `zone`=?"; + List> resultPaid = jdbcPenaltyTemplate.queryForList(sqlQuery_paid, depotid,zone); +*/ + // Fetch total out count for this depot + String sqlQuery_out = "SELECT IFNULL(SUM(unique_cattle_count), 0) AS cattlecount " + + "FROM ( SELECT COUNT(DISTINCT s1.id) AS unique_cattle_count " + + "FROM cc_step1 s1 JOIN cc_step3 s3 ON FIND_IN_SET(s1.id, s3.cinfoids) " + + "JOIN cc_step4 s4 ON s3.id = s4.cinfoid " + + "WHERE s1.isactive = 1 AND s1.isdelete = 0 AND s3.depotid = ? " + + "AND s1.zone = ? AND s1.ward=? " + + "AND DATE(s4.out_date) BETWEEN STR_TO_DATE(?, '%d-%m-%Y') " + + "AND STR_TO_DATE(?, '%d-%m-%Y') ) AS deduplicated_counts"; + List> resultOut = jdbcPenaltyTemplate.queryForList(sqlQuery_out, depotid,zone,ward,fromDate,toDate); + + System.out.println(sqlQuery_out); + /* + + // Fetch total paid count for this depot + String sqlQuery_pending = "SELECT count(s2.id) as TotalPending FROM `cc_step2` s2 " + + "WHERE (s2.`isactive`=1 AND s2.`isdelete`=0) AND (s2.`depotid`=? AND s2.`status`='in')"; + List> resultPending = jdbcPenaltyTemplate.queryForList(sqlQuery_pending, depotid); +*/ + // Add counts to the current depot details + Map detailedDepot = new HashMap<>(depot); + detailedDepot.put("Total", resultTotal.isEmpty() ? 0 : resultTotal.get(0).get("Total")); + //detailedDepot.put("TotalPaid", resultPaid.isEmpty() ? 0 : resultPaid.get(0).get("TotalPaid")); + detailedDepot.put("TotalOut", resultOut.isEmpty() ? 0 : resultOut.get(0).get("cattlecount")); + //detailedDepot.put("TotalPending", resultPending.isEmpty() ? 0 : resultPending.get(0).get("TotalPending")); + + // Add detailed depot to the response list + detailedResult.add(detailedDepot); + } + + // Prepare response + Map response = new HashMap<>(); + response.put("status", 200); + response.put("message", "Ward List Details"); + response.put("data", detailedResult); + + return Collections.singletonList(response); + } + + @Transactional + public List> inListReport( + MultiValueMap formData, + String fromDate, + String toDate, + String zone, + String ward, + String depotid, + String loginid) { + + String sqlQuery = "SELECT s1.`id`, s1.`category_id`, s1.`catch_by`, DATE_FORMAT(s1.`catch_date`, '%d-%m-%Y %H:%i') AS `catch_date`, s1.`latitude`, " + + " s1.`longitude`, s1.`zone`, s1.`ward`, s1.`streetid`, s1.`streetname`, s1.`image`, s1.`remarks`, " + + " DATE_FORMAT(s2.in_date, '%d-%m-%Y %H:%i') AS `in_date` , s2.in_by, " + + "CONCAT('"+fileBaseUrl+"/gccofficialapp/files',s1.`image`) as imageurl " + + " From `cc_step1` s1, `cc_step2` s2 WHERE (s1.`isactive`=1 AND s1.`isdelete`=0) " + + "AND (s1.id=s2.cinfoid AND s1.zone=? AND s1.ward=? AND s2.depotid=?) " + + "AND DATE(s2.in_date) BETWEEN STR_TO_DATE(?, '%d-%m-%Y') AND STR_TO_DATE(?, '%d-%m-%Y')"; + + //System.out.println(sqlQuery); + List> result = jdbcPenaltyTemplate.queryForList(sqlQuery,zone,ward,depotid,fromDate,toDate); + Map response = new HashMap<>(); + response.put("status", 200); + response.put("message", "Check IN List Details"); + response.put("data", result); + + return result; + } + + @Transactional + public List> outListReport( MultiValueMap formData, String fromDate, String toDate, + String zone, + String ward, + String depotid, String loginid) { - String sqlQuery = "SELECT zone, COUNT(*) AS zone_count FROM `cc_step1` WHERE " - + "DATE(catch_date) BETWEEN ? AND ? GROUP BY zone ORDER BY zone"; + String sqlQuery_out = "SELECT DISTINCT " + + " s1.`id`, " + + " s1.`category_id`, " + + " s1.`catch_by`, " + + " DATE_FORMAT(s1.`catch_date`, '%d-%m-%Y %H:%i') AS catch_date, " + + " s1.`latitude`, " + + " s1.`longitude`, " + + " s1.`zone`, " + + " s1.`ward`, " + + " s1.`streetid`, " + + " s1.`streetname`, " + + " s1.`remarks`, " + + " DATE_FORMAT(s2.`in_date`, '%d-%m-%Y %H:%i') AS in_date, " + + " s2.`in_by`, " + + " DATE_FORMAT(s4.`out_date`, '%d-%m-%Y %H:%i') AS `out_date`, " + + " s4.`out_by`, " + + " DATEDIFF(s4.`out_date`, s2.`in_date`) AS days_since_in_date, " + + " CONCAT('"+fileBaseUrl+"/gccofficialapp/files', s1.`image`) AS inImageurl, " + + " CONCAT('"+fileBaseUrl+"/gccofficialapp/files', s4.`image`) AS outImageurl " + + "FROM " + + " cc_step1 s1 " + + "JOIN " + + " cc_step3 s3 ON FIND_IN_SET(s1.id, s3.cinfoids) " + + "JOIN " + + " cc_step4 s4 ON s3.id = s4.cinfoid " + + "JOIN " + + " cc_step2 s2 ON s1.id = s2.cinfoid " + + "WHERE " + + " s1.isactive = 1 " + + " AND s1.isdelete = 0 " + + " AND s1.zone = ? " + + " AND s1.ward = ? " + + " AND s3.depotid = ? " + + " AND DATE(s4.out_date) BETWEEN STR_TO_DATE(?, '%d-%m-%Y') " + + " AND STR_TO_DATE(?, '%d-%m-%Y')"; + + //System.out.println(sqlQuery); + List> result = jdbcPenaltyTemplate.queryForList(sqlQuery_out,zone,ward,depotid,fromDate,toDate); + Map response = new HashMap<>(); + + List> detailedResult = new ArrayList<>(); + + for (Map cattle : result) { + Object noOfDayObject = cattle.get("days_since_in_date"); + + int days = (noOfDayObject != null) ? Integer.parseInt(noOfDayObject.toString()) : 0; + + int baseAmount = 5000; + int extraChargePerDay = 1000; + int fineAmount = days <= 2 ? baseAmount : baseAmount + ((days - 2) * extraChargePerDay); + + // Add fine amount to the current record + Map detailedCattle = new HashMap<>(cattle); + detailedCattle.put("fineAmount", fineAmount); + + detailedResult.add(detailedCattle); + } + + response.put("status", 200); + response.put("message", "Check Out List Details"); + response.put("data", detailedResult); + + return Collections.singletonList(response); + } + /* + @Transactional + public List> zoneReport( + MultiValueMap formData, + String fromDate, + String toDate, + String loginid) { + + String sqlQuery = "SELECT ward, COUNT(*) AS count " + + "FROM `cc_step1` " + + "WHERE catch_date BETWEEN STR_TO_DATE(?, '%d-%m-%Y') AND STR_TO_DATE(?, '%d-%m-%Y') " + + "GROUP BY ward"; if(loginid!=null && !loginid.isEmpty() && !loginid.isBlank()) { sqlQuery= sqlQuery +" AND `challan_by`='"+loginid+"'"; @@ -767,7 +1479,7 @@ public class CattleCatchService { List> result = jdbcPenaltyTemplate.queryForList(sqlQuery,fromDate,toDate); Map response = new HashMap<>(); response.put("status", 200); - response.put("message", "Challan Details"); + response.put("message", "Zone List Details"); response.put("data", result); return result; @@ -782,7 +1494,7 @@ public class CattleCatchService { String loginid) { String sqlQuery = "SELECT ward, COUNT(*) AS zone_count FROM `cc_step1` WHERE " - + "zone=? AND DATE(catch_date) BETWEEN ? AND ? GROUP BY ward ORDER BY ward"; + + "zone=? AND DATE(catch_date) BETWEEN STR_TO_DATE(?, '%d-%m-%Y') AND STR_TO_DATE(?, '%d-%m-%Y') GROUP BY ward ORDER BY ward"; if(loginid!=null && !loginid.isEmpty() && !loginid.isBlank()) { sqlQuery= sqlQuery +" AND `challan_by`='"+loginid+"'"; @@ -792,9 +1504,10 @@ public class CattleCatchService { List> result = jdbcPenaltyTemplate.queryForList(sqlQuery,zone,fromDate,toDate); Map response = new HashMap<>(); response.put("status", 200); - response.put("message", "Challan Details"); + response.put("message", "Ward List Details"); response.put("data", result); return result; } + */ } diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/penalty/service/PenaltyServicePOS.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/penalty/service/PenaltyServicePOS.java index 262ead8..cd974cb 100644 --- a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/penalty/service/PenaltyServicePOS.java +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/penalty/service/PenaltyServicePOS.java @@ -268,8 +268,12 @@ public class PenaltyServicePOS { String loginId, String violatorName, String violatorPhone, + String violatorCompany, String ton, String amount, + String tid, + String mid, + String serialNumber, MultipartFile file) { Map response = new HashMap<>(); @@ -279,11 +283,11 @@ public class PenaltyServicePOS { String sqlQuery = "INSERT INTO `penalty_challan`(`category_id`, `image`, `latitude`, `longitude`, " + "`zone`, `ward`, `challan_by`, " - + "`violator_name`, `violator_phone`, `ton`, `fine_amount`,`orderid`) " - + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"; + + "`violator_name`, `violator_phone`, `ton`, `fine_amount`,`orderid`,`violator_company`," + + "`tid`, `mid`, `serial_number`) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; KeyHolder keyHolder = new GeneratedKeyHolder(); - try { int affectedRows = jdbcPenaltyTemplate.update(new PreparedStatementCreator() { @Override @@ -301,6 +305,10 @@ public class PenaltyServicePOS { ps.setString(10, ton); ps.setString(11, amount); ps.setString(12, orderid); + ps.setString(13, violatorCompany); + ps.setString(14, tid); + ps.setString(15, mid); + ps.setString(16, serialNumber); return ps; } }, keyHolder); @@ -310,8 +318,8 @@ public class PenaltyServicePOS { lastInsertId = (generatedId != null) ? generatedId.intValue() : 0; //CONCAT('"+fileBaseUrl+"/gccofficialapp/files', cp.photo_url) AS photos, String sqlQuery_txt = "SELECT `category_id`,CONCAT('"+fileBaseUrl+"/gccofficialapp/files',`image`) as imageurl, `latitude`, `longitude`, `zone`, `ward`, " - + "`challan_by`, `violator_name`, `violator_phone`, `ton`, " - + "`fine_amount`,`orderid` From `penalty_challan` WHERE id='"+lastInsertId+"' LIMIT 1"; + + "`challan_by`, `violator_name`, `violator_phone`, `violator_company`, `ton`, " + + "`fine_amount`,`orderid`,`tid`,`mid`,`serial_number` From `penalty_challan` WHERE id='"+lastInsertId+"' LIMIT 1"; List> result = jdbcPenaltyTemplate.queryForList(sqlQuery_txt); //response.put("insertid", lastInsertId); @@ -320,6 +328,8 @@ public class PenaltyServicePOS { //response.put("orderid", orderid); response.put("data", result); + updateZoneWard(lastInsertId,loginId); // Update Zone and ward details + System.out.println("A new Penalty (Chellan) was generated successfully! Insert ID: " + generatedId); } else { response.put("status", 201); @@ -347,6 +357,37 @@ public class PenaltyServicePOS { return Collections.singletonList(response); } + public String updateZoneWard(int id, String loginid) { + // Select query to fetch data from the user_zone table + String sqluserLocation = "SELECT `SNO`, `ID`, `USER_NAME`, `FIRST_NAME`, `LOC_FLAG`, `LOC`, `ACTUAL_LOC`, `ZONE_HQ` " + + "FROM `user_zone` WHERE `ID`=?"; + // Fetch the result from the query (assuming only one row is returned) + List> result = jdbcPenaltyTemplate.queryForList(sqluserLocation, loginid); + + if (result.isEmpty()) { + System.out.println( "Challan User Loaction update: Error: User not found."); + // If no result is found, return an error message + return "Error: User not found."; + + } + + // Extract values from the result map (assuming the first record) + Map userZoneData = result.get(0); + String locFlag = (String) userZoneData.get("LOC_FLAG"); + String loc = (String) userZoneData.get("LOC"); + String actualLoc = (String) userZoneData.get("ACTUAL_LOC"); + String zoneHq = (String) userZoneData.get("ZONE_HQ"); + + // Update query to update the penalty_challan table using the fetched values + String sqlQuery = "UPDATE penalty_challan SET `LOC_FLAG` = ?, `LOC` = ?, `ACTUAL_LOC` = ?, `ZONE_HQ` = ? WHERE id = ? LIMIT 1"; + + // Execute the update query using the values fetched from user_zone table + jdbcPenaltyTemplate.update(sqlQuery, locFlag, loc, actualLoc, zoneHq, id); + + System.out.println( "Challan User Loaction Updated (id, loginid): " + id +" , " + loginid); + return "success"; // Return success after the update + } + @Transactional public List> getChallanPOSData( MultiValueMap formData, @@ -485,7 +526,7 @@ public class PenaltyServicePOS { updatePaymentStatus(txnId, transactionResponseStatus); - // Fetch inserted data for response, joining `penalty_challan` and `bank_transactions` + // Fetch inserted data for response, joining `penalty_challan` and `bank_transactions` String sqlQuery_joined = "SELECT pc.category_id, CONCAT('" + fileBaseUrl + "/gccofficialapp/files', pc.image) as imageurl, " + "pc.latitude, pc.longitude, pc.zone, pc.ward, pc.challan_by, " + "pc.violator_name, pc.violator_phone, pc.ton, pc.fine_amount, pc.orderid, pc.status, " @@ -497,22 +538,141 @@ public class PenaltyServicePOS { System.out.println(sqlQuery_joined); // Execute the query List> result = jdbcPenaltyTemplate.queryForList(sqlQuery_joined, lastInsertId); - /* - // Fetch inserted data for response - String sqlQuery_challan = "SELECT `category_id`,CONCAT('"+fileBaseUrl+"/gccofficialapp/files',`image`) as imageurl, `latitude`, `longitude`, `zone`, `ward`, " - + "`challan_by`, `violator_name`, `violator_phone`, `ton`, " - + "`fine_amount`, `orderid`, `status` From `penalty_challan` WHERE (`isactive`=1 AND `isdelete`=0) " - + "AND `orderid`='"+txnId+"' LIMIT 1"; - - List> result = jdbcPenaltyTemplate.queryForList(sqlQuery_challan, lastInsertId); + response.put("status", 200); + response.put("message", "Transaction stored successfully!"); + response.put("data", result); + } else { + response.put("status", 201); + response.put("message", "Failed to store the transaction."); + response.put("data", ""); + } + } catch (DataAccessException e) { + response.put("status", 500); + response.put("message", "Database error while storing transaction."); + response.put("error", e.getMessage()); + e.printStackTrace(); // This will give you more detail in logs + } + } else { + response.put("status", 400); + response.put("message", "Transaction failed or invalid status."); + } + + return Collections.singletonList(response); + } + + @Transactional + public List> storeFailedBankTransaction(Map transactionData) { + + Map response = new HashMap<>(); + int lastInsertId = 0; + + // Extract data from the JSON object + String transactionResponseStatus = (String) transactionData.get("transactionResponseStatus"); + + // Check if the transaction was successful + if ("Transaction cancelled".equalsIgnoreCase(transactionResponseStatus)) { + + String mid = (String) transactionData.get("mid"); + String tid = (String) transactionData.get("tid"); + String txnId = (String) transactionData.get("txnId"); + + // Fetch nested transaction response data + Map txnResponseData = (Map) transactionData.get("txnResponseData"); + + String bankName = (String) txnResponseData.get("bankName"); + String batchNumber = (String) txnResponseData.get("batchNumber"); + String transactionTitle = (String) txnResponseData.get("transactionTitle"); + String txnAID = (String) txnResponseData.get("txnAID"); + String txnApprCode = (String) txnResponseData.get("txnApprCode"); + String txnCardNo = (String) txnResponseData.get("txnCardNo"); + String txnCardType = (String) txnResponseData.get("txnCardType"); + String txnDate = (String) txnResponseData.get("txnDate"); + String txnInvoice = (String) txnResponseData.get("txnInvoice"); + String txnMode = (String) txnResponseData.get("txnMode"); + String txnRefNo = (String) txnResponseData.get("txnRefNo"); + String txnTC = (String) txnResponseData.get("txnTC"); + String txnTSI = (String) txnResponseData.get("txnTSI"); + String txnTVR = (String) txnResponseData.get("txnTVR"); + String txnTime = (String) txnResponseData.get("txnTime"); + + // Convert transaction amount properly + //Double transactionAmount = Double.valueOf((String) txnResponseData.get("transactionAmount")); + + // Get the transactionAmount from txnResponseData + String transactionAmountStr = (String) txnResponseData.get("transactionAmount"); + + // Check if the transactionAmount is not null and not empty before converting + Double transactionAmountTemp = null; + + if (transactionAmountStr != null && !transactionAmountStr.trim().isEmpty()) { + try { + // Convert the valid string to a Double + transactionAmountTemp = Double.valueOf(transactionAmountStr); + } catch (NumberFormatException e) { + // Handle the case where the string cannot be parsed to a Double // Log the error or throw a custom exception + System.out.println("Error: Unable to parse transactionAmount to Double. " + e.getMessage()); + transactionAmountTemp = 0.0; // Set to a default value or handle as needed + } + } else { + // Handle the case where transactionAmount is empty or null + transactionAmountTemp = 0.0; // Default value or handle as needed + } + + Double transactionAmount = transactionAmountTemp; + + String sqlQuery = "INSERT INTO bank_failed_transactions (mid, tid, txnId, bankName, batchNumber, transactionAmount, " + + "transactionTitle, txnAID, txnApprCode, txnCardNo, txnCardType, txnDate, txnInvoice, txnMode, txnRefNo, " + + "txnTC, txnTSI, txnTVR, txnTime) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; + + KeyHolder keyHolder = new GeneratedKeyHolder(); + + try { + int affectedRows = jdbcPenaltyTemplate.update(new PreparedStatementCreator() { + @Override + public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { + PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[]{"id"}); + ps.setString(1, mid); + ps.setString(2, tid); + ps.setString(3, txnId); + ps.setString(4, bankName); + ps.setString(5, batchNumber); + ps.setDouble(6, transactionAmount); + ps.setString(7, transactionTitle); + ps.setString(8, txnAID); + ps.setString(9, txnApprCode); + ps.setString(10, txnCardNo); + ps.setString(11, txnCardType); + ps.setString(12, txnDate); + ps.setString(13, txnInvoice); + ps.setString(14, txnMode); + ps.setString(15, txnRefNo); + ps.setString(16, txnTC); + ps.setString(17, txnTSI); + ps.setString(18, txnTVR); + ps.setString(19, txnTime); + return ps; + } + }, keyHolder); + + if (affectedRows > 0) { + Number generatedId = keyHolder.getKey(); + lastInsertId = (generatedId != null) ? generatedId.intValue() : 0; - // Fetch inserted data for response - String sqlQuery_txt = "SELECT mid, tid, txnId, bankName, batchNumber, transactionAmount, " - + "transactionTitle, txnCardNo, txnDate, txnInvoice, txnMode, txnRefNo " - + "FROM bank_transactions WHERE id = ? LIMIT 1"; + updatePaymentStatus(txnId, transactionResponseStatus); - List> result = jdbcPenaltyTemplate.queryForList(sqlQuery_txt, lastInsertId); - */ + // Fetch inserted data for response, joining `penalty_challan` and `bank_transactions` + String sqlQuery_joined = "SELECT pc.category_id, CONCAT('" + fileBaseUrl + "/gccofficialapp/files', pc.image) as imageurl, " + + "pc.latitude, pc.longitude, pc.zone, pc.ward, pc.challan_by, " + + "pc.violator_name, pc.violator_phone, pc.ton, pc.fine_amount, pc.orderid, pc.status, " + + "bt.mid, bt.tid, bt.txnId, bt.bankName, bt.batchNumber, bt.transactionAmount, bt.transactionTitle, " + + "bt.txnCardNo, bt.txnDate, bt.txnInvoice, bt.txnMode, bt.txnRefNo " + + "FROM penalty_challan pc " + + "LEFT JOIN bank_transactions bt ON pc.orderid = bt.txnId " + + "WHERE pc.isactive = 1 AND pc.isdelete = 0 AND bt.txnId = ? LIMIT 1"; + System.out.println(sqlQuery_joined); + // Execute the query + List> result = jdbcPenaltyTemplate.queryForList(sqlQuery_joined, txnId); response.put("status", 200); response.put("message", "Transaction stored successfully!"); response.put("data", result); diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/service/OfficialAPIService.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/service/OfficialAPIService.java index fd4bb27..ed393ab 100644 --- a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/service/OfficialAPIService.java +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/service/OfficialAPIService.java @@ -386,8 +386,10 @@ public class OfficialAPIService { SqlQuery="SELECT *,CONCAT('https://gccservices.in/gccofficialapp/files/app_icon/menu/', icon_url) " + "AS iconUrl FROM `modules` WHERE `ISACTIVE`=1 AND `id` IN ("+menus+") "; if(departmentId!=null && !departmentId.isEmpty() && !departmentId.isBlank()) { - SqlQuery=SqlQuery+" AND `departmentId_id`='"+departmentId+"'"; + SqlQuery=SqlQuery+" AND `departmentId_id`='"+departmentId+"' "; } + + SqlQuery = SqlQuery+" ORDER BY `orderby`, `name` ASC"; List> result = jdbcActivityTemplate.queryForList(SqlQuery); return result; } @@ -424,7 +426,7 @@ public class OfficialAPIService { } SqlQuery="SELECT *,CONCAT('https://gccservices.in/gccofficialapp/files/app_icon/menu/', icon_url) " - + "AS iconUrl FROM `menuitem` WHERE `ISACTIVE`=1 AND `module_id`=? AND `id` IN ("+menuitem+")"; + + "AS iconUrl FROM `menuitem` WHERE `ISACTIVE`=1 AND `module_id`=? AND `id` IN ("+menuitem+") ORDER BY `orderby`, `name` ASC"; System.out.println(SqlQuery); List> result = jdbcActivityTemplate.queryForList(SqlQuery,menuId); diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/swmbwg/controller/APIController.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/swmbwg/controller/APIController.java index 1327ee0..84912ae 100644 --- a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/swmbwg/controller/APIController.java +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/swmbwg/controller/APIController.java @@ -50,12 +50,26 @@ public class APIController { @RequestParam(value="serviceprovider", required = false) String serviceprovider, @RequestParam(value="serviceproviderid", required = false) String serviceproviderid, @RequestParam(value="loginId", required = false) String cby, - @RequestParam(value = "image", required = false) MultipartFile filedata + @RequestParam(value = "image", required = false) MultipartFile filedata, + @RequestParam(value = "file", required = false) MultipartFile filedata2 ){ return activity.saveRequest(latitude, longitude, zone, ward, streetid, streetname, location, classid, typeid, qtyofwaste, onsiteprocessing, serviceprovider, - serviceproviderid, cby, filedata); + serviceproviderid, cby, filedata, filedata2); + } + + @GetMapping(value="/getServiceProviderPendingList") + public List getServiceProviderPendingList(@RequestParam(value="loginId", required = false) String cby){ + return activity.getServiceProviderPendingList(cby); + } + + @PostMapping(value="/updateServiceProviderImg") + public List updateServiceProviderImg( + @RequestParam(value="did", required = true) String did, + @RequestParam(value = "file", required = true) MultipartFile filedata2 + ){ + return activity.updateServiceProviderImg(did,filedata2); } @GetMapping(value="/getZoneWiseCount") diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/swmbwg/service/activity.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/swmbwg/service/activity.java index 4f1178a..d32e00d 100644 --- a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/swmbwg/service/activity.java +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/swmbwg/service/activity.java @@ -187,12 +187,13 @@ public class activity { public List> saveRequest(String latitude, String longitude, String zone, String ward, String streetid, String streetname, String location, String classtxt, String type, String qtyofwaste, String onsiteprocessing, - String serviceprovider, String serviceproviderid, String cby, MultipartFile file) { + String serviceprovider, String serviceproviderid, String cby, MultipartFile file, MultipartFile file2) { List> result = null; Map response = new HashMap<>(); int lastInsertId = 0; String image = ""; + String image2 = ""; // Handle file upload if a file is provided if (file != null && !file.isEmpty()) { @@ -200,14 +201,22 @@ public class activity { var month = DateTimeUtil.getCurrentMonth(); image = fileUpload(year, month, file); } + + // Handle file upload if a file is provided + if (file2 != null && !file2.isEmpty()) { + var year = DateTimeUtil.getCurrentYear(); + var month = DateTimeUtil.getCurrentMonth(); + image2 = fileUpload(year, month, file2); + } String processingimg = image; + String serviceproviderimg = image2; String sqlQuery = "INSERT INTO `swm_bwg_data`" + "(`latitude`, `longitude`, `zone`, `ward`, `streetid`, " + "`streetname`, `location`, `class`, `type`, `qtyofwaste`, `onsiteprocessing`, " - + "`processingimg`, `serviceprovider`, `serviceproviderid`, `cby`) " - + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + + "`processingimg`, `serviceprovider`, `serviceproviderid`, `cby`,`serviceproviderimg`) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; KeyHolder keyHolder = new GeneratedKeyHolder(); @@ -231,6 +240,7 @@ public class activity { ps.setString(13, serviceprovider); ps.setString(14, serviceproviderid); ps.setString(15, cby); + ps.setString(16, serviceproviderimg); return ps; } }, keyHolder); @@ -268,6 +278,67 @@ public class activity { return Collections.singletonList(response); } + public List> getServiceProviderPendingList(String cby){ + + String sqlQuery = "SELECT sbd.*," + + "CONCAT('"+fileBaseUrl+"/gccofficialapp/files', sbd.processingimg) AS photos, " + + "CONCAT('"+fileBaseUrl+"/gccofficialapp/files', sbd.serviceproviderimg) AS providerphotos, " + + "sbc.name as classname, " + + "sbt.name as typename, " + + "spl.name as serviceprovidername " + + "FROM " + + "`swm_bwg_data` sbd, " + + "`swm_bwg_class` sbc, " + + "`swm_bwg_types` sbt, " + + "`swm_bwg_service_provider_list` spl " + + "WHERE (sbd.class=sbc.cid AND sbd.type=sbt.tid AND sbd.serviceproviderid=spl.splid) " + + "AND(`serviceprovider`='Engaged' AND `cby`= ?) AND `serviceproviderimg`=''"; + + List> result = jdbcBWGTemplate.queryForList(sqlQuery,cby); + Map response = new HashMap<>(); + response.put("status", "Success"); + response.put("message", "SWM - BWG Service Provider image upload pending list"); + response.put("data", result); + + return Collections.singletonList(response); + } + + + public List> updateServiceProviderImg(String did, MultipartFile file2) { + String image2=""; + // Handle file upload if a file is provided + if (file2 != null && !file2.isEmpty()) { + var year = DateTimeUtil.getCurrentYear(); + var month = DateTimeUtil.getCurrentMonth(); + image2 = fileUpload(year, month, file2); + } + + String sqlQuery = "UPDATE `swm_bwg_data` SET `serviceproviderimg` = ? WHERE `did` = ? "; + jdbcBWGTemplate.update(sqlQuery, image2, did); + + String sqlQueryList = "SELECT sbd.*," + + "CONCAT('"+fileBaseUrl+"/gccofficialapp/files', sbd.processingimg) AS photos, " + + "CONCAT('"+fileBaseUrl+"/gccofficialapp/files', sbd.serviceproviderimg) AS providerphotos, " + + "sbc.name as classname, " + + "sbt.name as typename, " + + "spl.name as serviceprovidername " + + "FROM " + + "`swm_bwg_data` sbd, " + + "`swm_bwg_class` sbc, " + + "`swm_bwg_types` sbt, " + + "`swm_bwg_service_provider_list` spl " + + "WHERE (sbd.class=sbc.cid AND sbd.type=sbt.tid AND sbd.serviceproviderid=spl.splid) " + + "AND(`serviceprovider`='Engaged' AND `did`= ?)"; + + List> result = jdbcBWGTemplate.queryForList(sqlQueryList,did); + + Map response = new HashMap<>(); + response.put("status", "Success"); + response.put("message", "SWM - BWG Service Provider image uploaded successfuly"); + response.put("data", result); + return Collections.singletonList(response); + } + public List> getZoneWiseCount(){ String sqlQuery = "SELECT sbd.zone, count(sbd.did) totalcount FROM `swm_bwg_data` sbd " @@ -303,6 +374,7 @@ public class activity { String sqlQuery = "SELECT sbd.*," + "CONCAT('"+fileBaseUrl+"/gccofficialapp/files', sbd.processingimg) AS photos, " + + "CONCAT('"+fileBaseUrl+"/gccofficialapp/files', sbd.serviceproviderimg) AS providerphotos, " + "sbc.name as classname, " + "sbt.name as typename, " + "spl.name as serviceprovidername " diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/toilets/controller/APIController.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/toilets/controller/APIController.java new file mode 100644 index 0000000..621a165 --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/toilets/controller/APIController.java @@ -0,0 +1,143 @@ +package in.gov.chennaicorporation.mobileservice.toilets.controller; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.util.MultiValueMap; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +import in.gov.chennaicorporation.mobileservice.toilets.service.activity; + +@RequestMapping("/gccofficialapp/api/toilets/") +@RestController("gccofficialappstoilets") +public class APIController { + @Autowired + private activity activity; + + @GetMapping(value="/getToiletsList") + public List getToiletsList(@RequestParam(value="loginId", required = true) String cby){ + return activity.getToiletsList(cby); + } + + @PostMapping(value="/updateToiletLocation") + public List updateToiletLocation( + @RequestParam(value="loginId", required = true) String cby, + @RequestParam(value="toilet_id", required = true) String toilet_id, + @RequestParam(value="latitude", required = true) String latitude, + @RequestParam(value="longitude", required = true) String longitude, + @RequestParam(value = "file", required = false) MultipartFile filedata + ){ + return activity.updateToiletLocation(toilet_id,latitude, longitude, filedata); + } + + @GetMapping("/getToiletsListWithButton") + public List getToiletsListWithButton( + @RequestParam(value = "loginId", required = false) String cby) { + return activity.getToiletsListWithButton(cby); + } + + @GetMapping(value="/getQuestionsList") + public List getQuestionsList(@RequestParam(value="loginId", required = false) String cby){ + return activity.getQuestionsList(); + } + + @PostMapping(value="/addNewToilet") + public List addNewToilet( + @RequestParam(value="latitude", required = true) String latitude, + @RequestParam(value="longitude", required = true) String longitude, + @RequestParam(value="zone", required = true) String zone, + @RequestParam(value="ward", required = true) String ward, + @RequestParam(value="locality", required = true) String locality, + @RequestParam(value="name", required = true) String name, + @RequestParam(value="loginId", required = false) String cby, + @RequestParam(value = "file", required = false) MultipartFile filedata + ){ + return activity.addNewToilet(latitude, longitude, zone, ward, name, locality, cby, filedata); + } + + @GetMapping("/toiletlistbylatlong") + public List toiletlistbylatlong(@RequestParam MultiValueMap formData, + @RequestParam(value = "latitude", required = true) String latitude, + @RequestParam(value = "longitude", required = true) String longitude, + @RequestParam(value = "assetid", required = true) String id, + @RequestParam(value = "loginId", required = false) String loginId) { + return activity.toiletlistbylatlong(formData, latitude, longitude,id,loginId); + } + + @PostMapping(value="/saveFeedback") + public List saveFeedback( + @RequestParam(value="toilet_id", required = true) String toilet_id, + @RequestParam(value="loginId", required = true) String cby, + @RequestParam(value="latitude", required = true) String latitude, + @RequestParam(value="longitude", required = true) String longitude, + @RequestParam(value="zone", required = true) String zone, + @RequestParam(value="ward", required = true) String ward, + @RequestParam(value="q_1", required = false) String q_1, + @RequestParam(value="q_2", required = false) String q_2, + @RequestParam(value="q_3", required = false) String q_3, + @RequestParam(value="q_4", required = false) String q_4, + @RequestParam(value="q_5", required = false) String q_5, + @RequestParam(value="q_6", required = false) String q_6, + @RequestParam(value="q_7", required = false) String q_7, + @RequestParam(value="q_8", required = false) String q_8, + @RequestParam(value="q_9", required = false) String q_9, + @RequestParam(value="q_10", required = false) String q_10, + @RequestParam(value="q_11", required = false) String q_11, + @RequestParam(value="remarks", required = false) String remarks, + @RequestParam(value = "file", required = true) MultipartFile filedata + ){ + return activity.saveFeedback(toilet_id, cby, latitude, longitude, zone, ward, + q_1, q_2, q_3, q_4, q_5, q_6, q_7, q_8, q_9, q_10, q_11, + remarks, filedata); + } + + @GetMapping(value="/zoneReport") + public List zoneReport( + @RequestParam MultiValueMap formData, + @RequestParam(value="fromDate", required = true) String fromDate, + @RequestParam(value="toDate", required = true) String toDate, + @RequestParam(value="loginId", required = false) String cby + ){ + return activity.zoneReport(formData,fromDate,toDate,cby); + } + + @GetMapping(value="/wardReport") + public List wardReport( + @RequestParam MultiValueMap formData, + @RequestParam(value="fromDate", required = true) String fromDate, + @RequestParam(value="toDate", required = true) String toDate, + @RequestParam(value="zone", required = true) String zone, + @RequestParam(value="loginId", required = false) String cby + ){ + return activity.wardReport(formData,fromDate,toDate,zone,cby); + } + + @GetMapping(value="/toiletReport") + public List toiletReport( + @RequestParam MultiValueMap formData, + @RequestParam(value="fromDate", required = true) String fromDate, + @RequestParam(value="toDate", required = true) String toDate, + @RequestParam(value="ward", required = true) String ward, + @RequestParam(value="loginId", required = false) String cby + ){ + return activity.toiletReport(formData,fromDate,toDate,ward,cby); + } + + @GetMapping(value="/feedbackReport") + public List feedbackReport( + @RequestParam MultiValueMap formData, + @RequestParam(value="fromDate", required = true) String fromDate, + @RequestParam(value="toDate", required = true) String toDate, + @RequestParam(value="type", required = true) String type, + @RequestParam(value="toilet_id", required = true) String id, + @RequestParam(value="loginId", required = false) String cby + ){ + return activity.feedbackReport(formData,fromDate,toDate,type,id,cby); + } +} diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/toilets/controller/package-info.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/toilets/controller/package-info.java new file mode 100644 index 0000000..ec7dd5c --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/toilets/controller/package-info.java @@ -0,0 +1 @@ +package in.gov.chennaicorporation.mobileservice.toilets.controller; \ No newline at end of file diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/toilets/package-info.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/toilets/package-info.java new file mode 100644 index 0000000..3caf3c4 --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/toilets/package-info.java @@ -0,0 +1 @@ +package in.gov.chennaicorporation.mobileservice.toilets; \ No newline at end of file diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/toilets/service/activity.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/toilets/service/activity.java new file mode 100644 index 0000000..68513c6 --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/toilets/service/activity.java @@ -0,0 +1,758 @@ +package in.gov.chennaicorporation.mobileservice.toilets.service; + +import java.awt.image.BufferedImage; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.SecureRandom; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.time.LocalTime; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; + +import javax.imageio.ImageIO; +import javax.imageio.ImageWriteParam; +import javax.imageio.ImageWriter; +import javax.imageio.stream.ImageOutputStream; +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.core.env.Environment; +import org.springframework.dao.DataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.PreparedStatementCreator; +import org.springframework.jdbc.support.GeneratedKeyHolder; +import org.springframework.jdbc.support.KeyHolder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.MultiValueMap; +import org.springframework.web.multipart.MultipartFile; + +import in.gov.chennaicorporation.mobileservice.gccactivity.service.DateTimeUtil; + +@Service("gccofficialappstoiletsactivity") +public class activity { + private JdbcTemplate jdbcToiletsTemplate; + private final Environment environment; + private String fileBaseUrl; + + private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + private static final int STRING_LENGTH = 15; + private static final Random RANDOM = new SecureRandom(); + + @Autowired + public void setDataSource(@Qualifier("mysqlToiletsDataSource") DataSource toiletsDataSource) { + this.jdbcToiletsTemplate = new JdbcTemplate(toiletsDataSource); + } + + @Autowired + public activity(Environment environment) { + this.environment = environment; + this.fileBaseUrl=environment.getProperty("fileBaseUrl"); + } + + 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(); + } + + private byte[] compressImage(BufferedImage image, float quality) throws IOException { + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(byteArrayOutputStream); + + ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next(); + writer.setOutput(imageOutputStream); + + 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.dispose(); + imageOutputStream.close(); + + 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("toilets_foldername"); + var year = DateTimeUtil.getCurrentYear(); + var month = DateTimeUtil.getCurrentMonth(); + + uploadDirectory = uploadDirectory + serviceFolderName + year + "/" + month; + + 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 + String fileName = name + "_" + id + "_" + datetimetxt + "_" + file.getOriginalFilename(); + fileName = fileName.replaceAll("\\s+", ""); // Remove space on filename + + String filePath = uploadDirectory + "/" + fileName; + + String filepath_txt = "/" + serviceFolderName + year + "/" + month + "/" + 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, compressedBytes); + + System.out.println(filePath); + return filepath_txt; + + } catch (IOException e) { + e.printStackTrace(); + return "Failed to save file " + file.getOriginalFilename(); + } + } + + public static String getTypeBasedOnTime() { + // Get the current time + LocalTime now = LocalTime.now(); + + // Define morning and evening time ranges + LocalTime morningStart = LocalTime.of(1, 0); // 1:00 AM + LocalTime eveningStart = LocalTime.of(13, 0); // 1:00 PM + + // Check and return the appropriate type + if (now.isAfter(morningStart) && now.isBefore(eveningStart)) { + return "morning"; + } else { + return "evening"; + } + } + + public List> getToiletsList(String loginid) { + String sql = "SELECT *," + + " CONCAT('"+fileBaseUrl+"/gccofficialapp/files',image) AS photo " + + " FROM `gcc_toilet_list` WHERE `user_id`=? AND `isactive`=1 AND `gcc_app_updated`= 0 "; + List> result = jdbcToiletsTemplate.queryForList(sql,loginid); + Map response = new HashMap<>(); + response.put("status", "Success"); + response.put("message", "Toilets List."); + response.put("data", result); + + return Collections.singletonList(response); + } + + @Transactional + public List> updateToiletLocation(String id,String latitude, String longitude, MultipartFile file) { + Map response = new HashMap<>(); + String image = ""; + + // Handle file upload if a file is provided + if (file != null && !file.isEmpty()) { + var year = DateTimeUtil.getCurrentYear(); + var month = DateTimeUtil.getCurrentMonth(); + image = fileUpload(year, month, file); + } + + String toiletimg = image; + String sql = "UPDATE `gcc_toilet_list` SET `gcc_app_updated`=1, `latitude`=?, longitude=?, `image`=? WHERE `id`=?"; + jdbcToiletsTemplate.update(sql, latitude, longitude, toiletimg, id); + + + response.put("status", "success"); + response.put("message", "Toilet Data updated successfully!"); + System.out.println("Toilet Data updated successfully!! Update ID: " + id); + + return Collections.singletonList(response); + } + + public List> getToiletsListWithButton(String loginid) { + /* + String sql = "SELECT " + + " `gcc_toilet_list`.*, " + + " CONCAT('"+fileBaseUrl+"/gccofficialapp/files', `gcc_toilet_list`.`image`) AS photo, " + + " CASE " + + " WHEN `toilet_feedback`.`type` = 'morning' THEN true " + + " ELSE false " + + " END AS morning_feedback, " + + " CASE " + + " WHEN `toilet_feedback`.`type` = 'evening' THEN true " + + " ELSE false " + + " END AS evening_feedback " + + "FROM " + + " `gcc_toilet_list` " + + "LEFT JOIN " + + " `toilet_feedback` " + + " ON `toilet_feedback`.`toilet_id` = `gcc_toilet_list`.`id` " + + " AND DATE(`toilet_feedback`.`cdate`) = CURDATE() " + + "WHERE " + + " `gcc_toilet_list`.`user_id` = ? " + + " AND `gcc_toilet_list`.`isactive` = 1"; + */ + String sql ="SELECT " + + " `gcc_toilet_list`.*, " + + " CONCAT('" + fileBaseUrl + "/gccofficialapp/files', " + + " CASE " + + " WHEN `gcc_toilet_list`.`image` IS NULL OR `gcc_toilet_list`.`image` = '' " + + " THEN `toilet_feedback`.`image` " + + " ELSE `gcc_toilet_list`.`image` " + + " END " + + " ) AS photo, " + + " MAX(CASE WHEN `toilet_feedback`.`type` = 'morning' THEN true ELSE false END) AS morning_feedback, " + + " MAX(CASE WHEN `toilet_feedback`.`type` = 'evening' THEN true ELSE false END) AS evening_feedback " + + "FROM " + + " `gcc_toilet_list` " + + "LEFT JOIN " + + " `toilet_feedback` " + + " ON `toilet_feedback`.`toilet_id` = `gcc_toilet_list`.`id` " + + " AND DATE(`toilet_feedback`.`cdate`) = CURDATE() " + + "WHERE " + + " `gcc_toilet_list`.`user_id` = ? " + + " AND `gcc_toilet_list`.`isactive` = 1 AND `gcc_app_updated`= 1 " + + "GROUP BY " + + " `gcc_toilet_list`.`id`"; + + List> result = jdbcToiletsTemplate.queryForList(sql,loginid); + Map response = new HashMap<>(); + response.put("status", "Success"); + response.put("message", "Toilets List with extra info."); + response.put("data", result); + + return Collections.singletonList(response); + } + + public List> getQuestionsList() { + String sql = "SELECT * FROM question_list WHERE isactive=1"; + List> result = jdbcToiletsTemplate.queryForList(sql); + Map response = new HashMap<>(); + response.put("status", "Success"); + response.put("message", "Toilet Question List."); + response.put("data", result); + + return Collections.singletonList(response); + } + + @Transactional + public List> addNewToilet(String latitude, + String longitude, String zone, String ward, String name, String locality, String cby, MultipartFile file) { + List> result = null; + Map response = new HashMap<>(); + int lastInsertId = 0; + + String image = ""; + + // Handle file upload if a file is provided + if (file != null && !file.isEmpty()) { + var year = DateTimeUtil.getCurrentYear(); + var month = DateTimeUtil.getCurrentMonth(); + image = fileUpload(year, month, file); + } + + String toiletimg = image; + + String sqlQuery = "INSERT INTO `gcc_toilet_list`(" + + "`zone`, `zone_name`, `ward`, `user_id`, `list`, " + + "`name`, `locality`, `latitude`, `longitude`, `toilet_availability`, " + + "`toilet_category`, `toilet_type`, `working_condition`, `refurbishment_type`,`image`) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + + KeyHolder keyHolder = new GeneratedKeyHolder(); + + try { + int affectedRows = jdbcToiletsTemplate.update(new PreparedStatementCreator() { + @Override + public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { + PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[] { "id" }); + ps.setString(1, zone); + ps.setString(2, ""); + ps.setString(3, ward); + ps.setString(4, cby); + ps.setString(5, ""); + ps.setString(6, name); + ps.setString(7, locality); + ps.setString(8, latitude); + ps.setString(9, longitude); + ps.setString(10, ""); + ps.setString(11, ""); + ps.setString(12, ""); + ps.setString(13, ""); + ps.setString(14, ""); + ps.setString(15, toiletimg); + return ps; + } + }, keyHolder); + + if (affectedRows > 0) { + Number generatedId = keyHolder.getKey(); + lastInsertId = (generatedId != null) ? generatedId.intValue() : 0; + response.put("insertId", lastInsertId); + response.put("status", "success"); + response.put("message", "A new asset was inserted successfully!"); + System.out.println("A new asset was inserted successfully! Insert ID: " + generatedId); + } else { + response.put("status", "error"); + response.put("message", "Failed to insert a new asset."); + } + } catch (DataAccessException e) { + System.out.println("Data Access Exception:"); + Throwable rootCause = e.getMostSpecificCause(); + if (rootCause instanceof SQLException) { + SQLException sqlException = (SQLException) rootCause; + System.out.println("SQL State: " + sqlException.getSQLState()); + System.out.println("Error Code: " + sqlException.getErrorCode()); + System.out.println("Message: " + sqlException.getMessage()); + response.put("status", "error"); + response.put("message", sqlException.getMessage()); + response.put("sqlState", sqlException.getSQLState()); + response.put("errorCode", sqlException.getErrorCode()); + } else { + System.out.println("Message: " + rootCause.getMessage()); + response.put("status", "error"); + response.put("message", rootCause.getMessage()); + } + } + + return Collections.singletonList(response); + } + + @Transactional + public List> toiletlistbylatlong( + MultiValueMap formData, + String latitude, + String longitude, + String id, + String loginid) { + + String sqlWhere = ""; + + if (latitude != null && longitude != null && !latitude.isBlank() && !latitude.isEmpty() && !longitude.isBlank() + && !longitude.isEmpty()) { + sqlWhere += " AND ((6371008.8 * acos(ROUND(cos(radians(" + latitude + + ")) * cos(radians(latitude)) * cos(radians(longitude) - radians(" + longitude + + ")) + sin(radians(" + latitude + ")) * sin(radians(latitude)), 9))) < 200)" + + " ORDER BY `id` DESC"; + } + + String sqlQuery = "SELECT *," + + " CONCAT('"+fileBaseUrl+"/gccofficialapp/files',image) AS photo " + + " FROM `gcc_toilet_list` WHERE `user_id`=? AND `isactive`=1 AND id = ?" // This is the starting part of WHERE clause + + sqlWhere; // Here the latitude and longitude condition gets appended if provided + + List> result = jdbcToiletsTemplate.queryForList(sqlQuery,loginid, id); + Map response = new HashMap<>(); + response.put("status", 200); + response.put("message", "Nearby toilet list."); + if(result.isEmpty()) { + response.put("message", "No toilet found nearby."); + } + response.put("data", result); + + return Collections.singletonList(response); + } + + @Transactional + public List> saveFeedback( + String toilet_id, + String cby, + String latitude, + String longitude, + String zone, + String ward, + String q_1, + String q_2, + String q_3, + String q_4, + String q_5, + String q_6, + String q_7, + String q_8, + String q_9, + String q_10, + String q_11, + String remarks, + MultipartFile file) { + List> result = null; + Map response = new HashMap<>(); + int lastInsertId = 0; + + String image = ""; + + // Handle file upload if a file is provided + if (file != null && !file.isEmpty()) { + var year = DateTimeUtil.getCurrentYear(); + var month = DateTimeUtil.getCurrentMonth(); + image = fileUpload(year, month, file); + } + + String feedbackimg = image; + String type = getTypeBasedOnTime(); // Get Morning & Evening + + String sqlQuery = "INSERT INTO `toilet_feedback`(" + + "`toilet_id`, `cby`, " + + "`q1`, `q2`, `q3`, `q4`, `q5`, `q6`, `q7`, `q8`, `q9`, `q10`, `q11`, " + + "`remarks`,`latitude`, `longitude`,`zone`,`ward`,`type`,`image`) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + + KeyHolder keyHolder = new GeneratedKeyHolder(); + + try { + int affectedRows = jdbcToiletsTemplate.update(new PreparedStatementCreator() { + @Override + public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { + PreparedStatement ps = connection.prepareStatement(sqlQuery, new String[] { "id" }); + ps.setString(1, toilet_id); + ps.setString(2, cby); + ps.setString(3, q_1); + ps.setString(4, q_2); + ps.setString(5, q_3); + ps.setString(6, q_4); + ps.setString(7, q_5); + ps.setString(8, q_6); + ps.setString(9, q_7); + ps.setString(10, q_8); + ps.setString(11, q_9); + ps.setString(12, q_10); + ps.setString(13, q_11); + ps.setString(14, remarks); + ps.setString(15, latitude); + ps.setString(16, longitude); + ps.setString(17, zone); + ps.setString(18, ward); + ps.setString(19, type); + ps.setString(20, feedbackimg); + return ps; + } + }, keyHolder); + + if (affectedRows > 0) { + Number generatedId = keyHolder.getKey(); + lastInsertId = (generatedId != null) ? generatedId.intValue() : 0; + response.put("insertId", lastInsertId); + response.put("status", "success"); + response.put("message", "A new feedback was inserted successfully!"); + System.out.println("A new feedback was inserted successfully! Insert ID: " + generatedId); + } else { + response.put("status", "error"); + response.put("message", "Failed to insert a new feedback. Asset ID:" + toilet_id); + } + } catch (DataAccessException e) { + System.out.println("Data Access Exception:"); + Throwable rootCause = e.getMostSpecificCause(); + if (rootCause instanceof SQLException) { + SQLException sqlException = (SQLException) rootCause; + System.out.println("SQL State: " + sqlException.getSQLState()); + System.out.println("Error Code: " + sqlException.getErrorCode()); + System.out.println("Message: " + sqlException.getMessage()); + response.put("status", "error"); + response.put("message", sqlException.getMessage()); + response.put("sqlState", sqlException.getSQLState()); + response.put("errorCode", sqlException.getErrorCode()); + } else { + System.out.println("Message: " + rootCause.getMessage()); + response.put("status", "error"); + response.put("message", rootCause.getMessage()); + } + } + + return Collections.singletonList(response); + } + + // Report + + @Transactional + public List> zoneReport( + MultiValueMap formData, + String fromDate, + String toDate, + String loginid) { + + + + String sqlQuery = "SELECT " + + " `gcc_toilet_list`.`zone`, " + + " COUNT(DISTINCT `gcc_toilet_list`.`id`) AS Total_Toilets, " + + " SUM(CASE " + + " WHEN `gcc_toilet_list`.`gcc_app_updated` = '0' THEN 1 " + + " ELSE 0 " + + " END) AS Enumeration_Pending, " + + " SUM(CASE " + + " WHEN `toilet_feedback`.`type` = 'morning' THEN 1 " + + " ELSE 0 " + + " END) AS Morning_Count, " + + " SUM(CASE " + + " WHEN `toilet_feedback`.`type` = 'evening' THEN 1 " + + " ELSE 0 " + + " END) AS Evening_Count " + + "FROM " + + " `gcc_toilet_list` " + + "LEFT JOIN " + + " `toilet_feedback` " + + " ON `toilet_feedback`.`toilet_id` = `gcc_toilet_list`.`id` " + + " AND DATE(`toilet_feedback`.`cdate`) BETWEEN STR_TO_DATE(?, '%d-%m-%Y') AND STR_TO_DATE(?, '%d-%m-%Y') " + + "WHERE " + //+ " `gcc_toilet_list`.`user_id` = ? AND " + + " `gcc_toilet_list`.`isactive` = 1 " + + "GROUP BY " + + " `gcc_toilet_list`.`zone` " + + "ORDER BY " + + " `gcc_toilet_list`.`zone`"; + + List> result = jdbcToiletsTemplate.queryForList(sqlQuery, fromDate, toDate); + Map response = new HashMap<>(); + response.put("status", 200); + response.put("message", "Zone report."); + if(result.isEmpty()) { + response.put("message", "No data found."); + } + response.put("data", result); + + return Collections.singletonList(response); + } + + @Transactional + public List> wardReport( + MultiValueMap formData, + String fromDate, + String toDate, + String zone, + String loginid) { + + + + String sqlQuery = "SELECT " + + " `gcc_toilet_list`.`ward`, " + + " COUNT(DISTINCT `gcc_toilet_list`.`id`) AS Total_Toilets, " + + " SUM(CASE " + + " WHEN `gcc_toilet_list`.`gcc_app_updated` = '0' THEN 1 " + + " ELSE 0 " + + " END) AS Enumeration_Pending, " + + " SUM(CASE " + + " WHEN `toilet_feedback`.`type` = 'morning' THEN 1 " + + " ELSE 0 " + + " END) AS Morning_Count, " + + " SUM(CASE " + + " WHEN `toilet_feedback`.`type` = 'evening' THEN 1 " + + " ELSE 0 " + + " END) AS Evening_Count " + + "FROM " + + " `gcc_toilet_list` " + + "LEFT JOIN " + + " `toilet_feedback` " + + " ON `toilet_feedback`.`toilet_id` = `gcc_toilet_list`.`id` " + + " AND DATE(`toilet_feedback`.`cdate`) BETWEEN STR_TO_DATE(?, '%d-%m-%Y') AND STR_TO_DATE(?, '%d-%m-%Y') " + + "WHERE " + + " `gcc_toilet_list`.`zone` = ? AND " + + " `gcc_toilet_list`.`isactive` = 1 " + + "GROUP BY " + + " `gcc_toilet_list`.`ward` " + + "ORDER BY " + + " `gcc_toilet_list`.`ward`"; + + List> result = jdbcToiletsTemplate.queryForList(sqlQuery, fromDate, toDate, zone); + Map response = new HashMap<>(); + response.put("status", 200); + response.put("message", "Ward report."); + if(result.isEmpty()) { + response.put("message", "No data found."); + } + response.put("data", result); + + return Collections.singletonList(response); + } + + @Transactional + public List> toiletReport( + MultiValueMap formData, + String fromDate, + String toDate, + String ward, + String loginid) { + + + + String sqlQuery = "SELECT " + + " `gcc_toilet_list`.`id`,`gcc_toilet_list`.`name`,`gcc_toilet_list`.`zone`,`gcc_toilet_list`.`ward`, " + + " CONCAT('"+fileBaseUrl+"/gccofficialapp/files', `gcc_toilet_list`.`image`) AS photo," + + " SUM(CASE " + + " WHEN `gcc_toilet_list`.`gcc_app_updated` = '0' THEN 1 " + + " ELSE 0 " + + " END) AS Enumeration_Pending, " + + " SUM(CASE " + + " WHEN `toilet_feedback`.`type` = 'morning' THEN 1 " + + " ELSE 0 " + + " END) AS Morning_Count, " + + " SUM(CASE " + + " WHEN `toilet_feedback`.`type` = 'evening' THEN 1 " + + " ELSE 0 " + + " END) AS Evening_Count " + + "FROM " + + " `gcc_toilet_list` " + + "LEFT JOIN " + + " `toilet_feedback` " + + " ON `toilet_feedback`.`toilet_id` = `gcc_toilet_list`.`id` " + + " AND DATE(`toilet_feedback`.`cdate`) BETWEEN STR_TO_DATE(?, '%d-%m-%Y') AND STR_TO_DATE(?, '%d-%m-%Y') " + + "WHERE " + + " `gcc_toilet_list`.`ward` = ? AND " + + " `gcc_toilet_list`.`isactive` = 1 " + + "GROUP BY " + + " `gcc_toilet_list`.`id` " + + "ORDER BY " + + " `gcc_toilet_list`.`id`"; + + List> result = jdbcToiletsTemplate.queryForList(sqlQuery, fromDate, toDate, ward); + Map response = new HashMap<>(); + response.put("status", 200); + response.put("message", "Toilet list report."); + if(result.isEmpty()) { + response.put("message", "No data found."); + } + response.put("data", result); + + return Collections.singletonList(response); + } + + @Transactional + public List> feedbackReport( + MultiValueMap formData, + String fromDate, + String toDate, + //String ward, + String type, + String toiletid, + String loginid) { + + String sqlQuery = "SELECT " + + " `gcc_toilet_list`.`id` as assetid, " + + " `gcc_toilet_list`.`name`, " + + " `gcc_toilet_list`.`zone`, " + + " `gcc_toilet_list`.`ward`, " + + " CONCAT('"+fileBaseUrl+"/gccofficialapp/files', `gcc_toilet_list`.`image`) AS toiletPhoto, " + + " DATE_FORMAT(`toilet_feedback`.`cdate`, '%d-%m-%Y %I:%i %p') as feedbackDate, " + + " `toilet_feedback`.*, " + + " CONCAT('"+fileBaseUrl+"/gccofficialapp/files', `toilet_feedback`.`image`) AS feedbackPhoto " + + "FROM " + + " `gcc_toilet_list` " + + "RIGHT JOIN " + + " `toilet_feedback` " + + " ON `toilet_feedback`.`toilet_id` = `gcc_toilet_list`.`id` " + + " AND `toilet_feedback`.`type` = ? " + + " AND DATE(`toilet_feedback`.`cdate`) BETWEEN STR_TO_DATE(?, '%d-%m-%Y') AND STR_TO_DATE(?, '%d-%m-%Y') " + + "WHERE " + + " `gcc_toilet_list`.`id` = ? " + + " AND `gcc_toilet_list`.`isactive` = 1 " + + "ORDER BY " + + " feedbackDate"; + + List> result = jdbcToiletsTemplate.queryForList(sqlQuery, type, fromDate, toDate, toiletid); + + // Questions + String sqlQuestion = "SELECT * FROM `question_list`"; + + List> question = jdbcToiletsTemplate.queryForList(sqlQuestion); + + // Prepare response + Map response = new HashMap<>(); + response.put("status", 200); + if (result.isEmpty()) { + response.put("message", "No data found."); + response.put("data", Collections.emptyList()); + response.put("question", Collections.emptyList()); + } else { + response.put("message", "Feedback list report."); + response.put("data", result); + response.put("question", question); + } + + return Collections.singletonList(response); + } + /* + @Transactional + public List> feedbackReport( + MultiValueMap formData, + String fromDate, + String toDate, + String type, + String toiletid, + String loginid) { + + // Fetch feedback data + String sqlQuery = "SELECT `gcc_toilet_list`.`id` as assetid,`gcc_toilet_list`.`name`,`gcc_toilet_list`.`zone`," + + "`gcc_toilet_list`.`ward`, CONCAT('https://gccservices.in/gccofficialapp/files', `gcc_toilet_list`.`image`) AS toiletPhoto," + + " DATE(`toilet_feedback`.`cdate`) as feedbackDate, " + + "`toilet_feedback`.*, CONCAT('https://gccservices.in/gccofficialapp/files', `toilet_feedback`.`image`) AS feedbackPhoto " + + "FROM `gcc_toilet_list` JOIN `toilet_feedback` ON `toilet_feedback`.`toilet_id` = `gcc_toilet_list`.`id` " + + "AND `toilet_feedback`.`type` = ? " + + "AND DATE(`toilet_feedback`.`cdate`) BETWEEN STR_TO_DATE(?, '%d-%m-%Y') " + + "AND STR_TO_DATE(?, '%d-%m-%Y') WHERE `gcc_toilet_list`.`id` = ? " + + "AND `gcc_toilet_list`.`isactive` = 1 GROUP BY `gcc_toilet_list`.`id` ORDER BY feedbackDate"; + + List> feedbackData = jdbcToiletsTemplate.queryForList(sqlQuery, type, fromDate, toDate, toiletid); + + // Fetch question data + String sqlQuestion = "SELECT * FROM `question_list`"; + List> questionData = jdbcToiletsTemplate.queryForList(sqlQuestion); + + // Map questions by ID for easy lookup + Map> questionMap = new HashMap<>(); + for (Map question : questionData) { + questionMap.put("q" + question.get("id"), question); + } + + // Enrich feedback data with question English and Tamil fields + for (Map feedback : feedbackData) { + for (int i = 1; i <= 7; i++) { // Assuming there are 7 questions (q1 to q7) + String questionKey = "q" + i; + if (feedback.containsKey(questionKey)) { + Map question = questionMap.get(questionKey); + if (question != null) { + feedback.put(questionKey + "_english", question.get("q_english")); + feedback.put(questionKey + "_tamil", question.get("q_tamil")); + } else { + feedback.put(questionKey + "_english", null); + feedback.put(questionKey + "_tamil", null); + } + } + } + } + + // Prepare response + Map response = new HashMap<>(); + response.put("status", 200); + if (feedbackData.isEmpty()) { + response.put("message", "No data found."); + response.put("data", Collections.emptyList()); + } else { + response.put("message", "Feedback list report."); + response.put("data", feedbackData); + } + + return Collections.singletonList(response); + } + */ +} diff --git a/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/toilets/service/package-info.java b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/toilets/service/package-info.java new file mode 100644 index 0000000..56b0047 --- /dev/null +++ b/mobileservice/src/main/java/in/gov/chennaicorporation/mobileservice/toilets/service/package-info.java @@ -0,0 +1 @@ +package in.gov.chennaicorporation.mobileservice.toilets.service; \ No newline at end of file diff --git a/mobileservice/src/main/resources/.DS_Store b/mobileservice/src/main/resources/.DS_Store index eefd1a6..16dfc65 100644 Binary files a/mobileservice/src/main/resources/.DS_Store and b/mobileservice/src/main/resources/.DS_Store differ diff --git a/mobileservice/src/main/resources/application.properties b/mobileservice/src/main/resources/application.properties index eafaf20..c169002 100644 --- a/mobileservice/src/main/resources/application.properties +++ b/mobileservice/src/main/resources/application.properties @@ -26,6 +26,7 @@ spring.servlet.multipart.max-file-size=20MB # Maximum request size (including all files) spring.servlet.multipart.max-request-size=20MB +spring.mvc.favicon.enabled=false fileBaseUrl=https://gccservices.in @@ -33,12 +34,14 @@ file.upload.directory=${user.dir}/gcc_mobile_service_uploads/ activity_foldername = asset_activity/ activity_new_asset_foldername = asset_images/ -brr_activity_foldername= brr_activity_images/ -sos_activity_foldername= sos_rescue_activity_images/ -penalty_foldername=penalty_activity/ -straydogs_foldername=stray_dogs/ -gccschools_foldername=schools_images/ -parks_playground_foldername=parks_playground_images/ -swm_bwg_foldername=swm_bwg/ -cattlecatch_foldername=cattlecatch_activity/ +brr_activity_foldername = brr_activity_images/ +sos_activity_foldername = sos_rescue_activity_images/ +penalty_foldername = penalty_activity/ +straydogs_foldername = stray_dogs/ +gccschools_foldername = schools_images/ +parks_playground_foldername = parks_playground_images/ +swm_bwg_foldername = swm_bwg/ +cattlecatch_foldername = cattlecatch_activity/ +hoardings_foldername = hoardings_activity/ +toilets_foldername = toilets_activity/ diff --git a/mobileservice/src/main/resources/static/assets/favicon.ico b/mobileservice/src/main/resources/static/assets/favicon.ico new file mode 100644 index 0000000..841b1eb Binary files /dev/null and b/mobileservice/src/main/resources/static/assets/favicon.ico differ diff --git a/mobileservice/src/main/resources/static/favicon.ico b/mobileservice/src/main/resources/static/favicon.ico new file mode 100644 index 0000000..841b1eb Binary files /dev/null and b/mobileservice/src/main/resources/static/favicon.ico differ